Created
February 18, 2019 05:06
-
-
Save apiarian/bc723bc6dfca5384a7167a48d48ce635 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 ( | |
"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] | |
} |
Author
apiarian
commented
Feb 18, 2019
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