Skip to content

Instantly share code, notes, and snippets.

@cwndrws
Created May 21, 2014 20:16
Show Gist options
  • Save cwndrws/75a2b8f92d96e2aeb083 to your computer and use it in GitHub Desktop.
Save cwndrws/75a2b8f92d96e2aeb083 to your computer and use it in GitHub Desktop.
Benchmark showing the proposed new way to stringify uuid's in gocql
package uuidStringBench
import (
"testing"
"github.com/gocql/gocql"
"fmt"
)
var (
u gocql.UUID
hexString = "0123456789abcdef"
b1, b2 byte
)
func init() {
u = gocql.TimeUUID()
}
func newWay(uuid gocql.UUID) string {
r := make([]byte, 36)
for i, b := range uuid {
b1 = hexString[b >> 4]
b2 = hexString[b &^ 240]
switch {
case i < 4:
r[i*2] = b1
r[(i*2)+1] = b2
case i >= 4 && i < 6:
r[(i*2)+1] = b1
r[(i*2)+2] = b2
case i >= 6 && i < 8:
r[(i*2)+2] = b1
r[(i*2)+3] = b2
case i >= 8 && i < 10:
r[(i*2)+3] = b1
r[(i*2)+4] = b2
case i >= 10:
r[(i*2)+4] = b1
r[(i*2)+5] = b2
}
}
r[8] = '-'
r[13] = '-'
r[18] = '-'
r[23] = '-'
return string(r)
}
func oldWay(uuid gocql.UUID) string {
return fmt.Sprintf("%x-%x-%x-%x-%x",
uuid[0:4], uuid[4:6], uuid[6:8], uuid[8:10], uuid[10:16])
}
func TestUUIDSame(t *testing.T) {
s1 := newWay(u)
s2 := oldWay(u)
if s1 != s2 {
t.Errorf("Strings did not match:\n%s\n%s\n", s1, s2)
}
}
func BenchmarkOldWay(b *testing.B) {
for i := 0; i < b.N; i++ {
oldWay(u)
}
}
func BenchmarkNewWay(b *testing.B) {
for i := 0; i < b.N; i++ {
newWay(u)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment