Skip to content

Instantly share code, notes, and snippets.

@vishr
Created January 26, 2015 22:25
Show Gist options
  • Save vishr/20c179973b3094fe047e to your computer and use it in GitHub Desktop.
Save vishr/20c179973b3094fe047e to your computer and use it in GitHub Desktop.

Revisions

  1. Vishal Rana created this gist Jan 26, 2015.
    78 changes: 78 additions & 0 deletions lookup_test.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,78 @@
    package test

    import (
    "sort"
    "testing"
    )

    type (
    People []*Person
    Person struct {
    Id int
    }
    )

    const (
    N = 256
    z = 2
    )

    var (
    m = map[int]*Person{}
    a = make(People, N)
    p *Person
    )

    func (p People) Len() int {
    return len(p)
    }

    func (p People) Swap(i, j int) {
    p[i], p[j] = p[j], p[i]
    }

    func (p People) Less(i, j int) bool {
    return p[i].Id < p[j].Id
    }

    func BenchmarkFindInMap(b *testing.B) {
    for i := 0; i < b.N; i++ {
    p = m[z]
    }
    }

    func BenchmarkFindInSlice(b *testing.B) {
    for i := 0; i < b.N; i++ {
    p = a[z]
    }
    }

    func BenchmarkFindInList(b *testing.B) {
    for i := 0; i < b.N; i++ {
    for j := 0; j < N; j++ {
    if j == z {
    break
    }
    }
    }
    }

    func BenchmarkFindInTree(b *testing.B) {
    for i := 0; i < b.N; i++ {
    sort.Search(len(a), func(i int) bool {
    return a[i].Id == z
    })
    }
    }

    func init() {
    // Populate map and slice
    for i := 0; i < N; i++ {
    p := &Person{i}
    m[i] = p
    a[i] = p
    }

    // Sort slice
    sort.Sort(a)
    }