Skip to content

Instantly share code, notes, and snippets.

@apiarian
Created February 18, 2019 05:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save apiarian/bc723bc6dfca5384a7167a48d48ce635 to your computer and use it in GitHub Desktop.
Save apiarian/bc723bc6dfca5384a7167a48d48ce635 to your computer and use it in GitHub Desktop.
package main
import (
"math/rand"
"sort"
"testing"
)
func BenchmarkInsertSorted(b *testing.B) {
data := make([]int, b.N)
for i := 0; i < b.N; i++ {
data[i] = rand.Int()
}
a := []int{}
for z := 0; z < len(data); z++ {
x := data[z]
i := sort.SearchInts(a, x)
if i >= len(a) || a[i] != x {
a = append(a, 0)
copy(a[i+1:], a[i:])
a[i] = x
}
}
}
func BenchmarkSortAfter(b *testing.B) {
data := make([]int, b.N)
for i := 0; i < b.N; i++ {
data[i] = rand.Int()
}
a := []int{}
for z := 0; z < len(data); z++ {
x := data[z]
a = append(a, x)
}
sort.Ints(a)
j := 0
for i := 1; i < len(a); i++ {
if a[j] == a[i] {
continue
}
j++
a[j] = a[i]
}
a = a[:j+1]
}
@apiarian
Copy link
Author

Yup, don't do this. Leave the sorting to the last possible moment if you can. Maybe make a write-ahead-log or something.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment