Created
January 25, 2017 18:08
-
-
Save arosh/64d463c33a7075383cd7553bd5f5f2fc to your computer and use it in GitHub Desktop.
type assertion is too slow
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"testing" | |
"errors" | |
) | |
var ( | |
ErrQueueEmpty = errors.New("Queue is empty") | |
) | |
type Queue struct { | |
container []interface{} | |
head int | |
tail int | |
} | |
func NewQueue() *Queue { | |
return &Queue{ | |
container: make([]interface{}, 0), | |
head: 0, | |
tail: 0, | |
} | |
} | |
func (q *Queue) Push(value interface{}) { | |
q.container = append(q.container, value) | |
q.tail++ | |
} | |
func (q *Queue) Shift() (interface{}, error) { | |
if q.IsEmpty() { | |
return nil, ErrQueueEmpty | |
} | |
ret := q.container[q.head] | |
q.head++ | |
return ret, nil | |
} | |
func (q *Queue) IsEmpty() bool { | |
return q.head >= q.tail | |
} | |
type IntQueue struct { | |
container *Queue | |
} | |
func NewIntQueue() *IntQueue { | |
return &IntQueue{ | |
container: NewQueue(), | |
} | |
} | |
func (q *IntQueue) Push(value int) { | |
q.container.Push(value) | |
} | |
func (q *IntQueue) Shift() (int, error) { | |
n, err := q.container.Shift() | |
if err != nil { | |
return 0, err | |
} else { | |
return n.(int), nil | |
} | |
} | |
func (q *IntQueue) IsEmpty() bool { | |
return q.container.IsEmpty() | |
} | |
func BenchmarkQueue(b *testing.B) { | |
queue := NewIntQueue() | |
b.ResetTimer() | |
for i := 0; i < b.N; i++ { | |
queue.Push(0) | |
} | |
for i := 0; i < b.N; i++ { | |
queue.Shift() | |
} | |
} | |
type IntQueue2 struct { | |
container []int | |
head int | |
tail int | |
} | |
func NewIntQueue2() *IntQueue2 { | |
return &IntQueue2{ | |
container: make([]int, 0), | |
head: 0, | |
tail: 0, | |
} | |
} | |
func (q *IntQueue2) Push(value int) { | |
q.container = append(q.container, value) | |
q.tail++ | |
} | |
func (q *IntQueue2) Shift() (int, error) { | |
if q.IsEmpty() { | |
return 0, ErrQueueEmpty | |
} | |
ret := q.container[q.head] | |
q.head++ | |
return ret, nil | |
} | |
func (q *IntQueue2) IsEmpty() bool { | |
return q.head >= q.tail | |
} | |
func BenchmarkQueue2(b *testing.B) { | |
queue := NewIntQueue2() | |
b.ResetTimer() | |
for i := 0; i < b.N; i++ { | |
queue.Push(0) | |
} | |
for i := 0; i < b.N; i++ { | |
queue.Shift() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment