Created
April 9, 2015 03:14
-
-
Save bfallik/8aac7b4821d2578b33ee to your computer and use it in GitHub Desktop.
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 blog | |
import ( | |
"testing" | |
) | |
type Advertisement struct { | |
ID int | |
Name string | |
CampaignID int | |
filler [10]int | |
} | |
var Ads []Advertisement | |
func ads() []Advertisement { | |
if len(Ads) == 0 { | |
Ads = make([]Advertisement, 1e6) | |
for i := range Ads { | |
// pathological worst case - every campaign ID is unique | |
Ads[i].CampaignID = i | |
} | |
} | |
return Ads | |
} | |
func bench(b *testing.B, fn func([]Advertisement), N int) { | |
ads := ads()[0:N] | |
b.ResetTimer() | |
for i := 0; i < b.N; i++ { | |
fn(ads) | |
} | |
} | |
func naive(ads []Advertisement) { | |
index := map[int][]Advertisement{} | |
for _, ad := range ads { | |
index[ad.CampaignID] = []Advertisement{ad} | |
} | |
} | |
func Benchmark_Naive_1e4(b *testing.B) { bench(b, naive, 1e4) } | |
func Benchmark_Naive_1e5(b *testing.B) { bench(b, naive, 1e5) } | |
func Benchmark_Naive_1e6(b *testing.B) { bench(b, naive, 1e6) } | |
func pointer(ads []Advertisement) { | |
index := map[int][]*Advertisement{} | |
for idx, ad := range ads { | |
index[ad.CampaignID] = []*Advertisement{&ads[idx]} | |
} | |
} | |
func Benchmark_Pointer_1e4(b *testing.B) { bench(b, pointer, 1e4) } | |
func Benchmark_Pointer_1e5(b *testing.B) { bench(b, pointer, 1e5) } | |
func Benchmark_Pointer_1e6(b *testing.B) { bench(b, pointer, 1e6) } | |
func position(ads []Advertisement) { | |
index := map[int][]int{} | |
for idx, ad := range ads { | |
index[ad.CampaignID] = []int{idx} | |
} | |
} | |
func Benchmark_Position_1e4(b *testing.B) { bench(b, position, 1e4) } | |
func Benchmark_Position_1e5(b *testing.B) { bench(b, position, 1e5) } | |
func Benchmark_Position_1e6(b *testing.B) { bench(b, position, 1e6) } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment