Browse Source

Switch from a map to a string slice..

benchmark perf is more than double (334ns/op -vs- 734ns/op)
master
jimi 9 years ago
parent
commit
e821387d95
  1. 22
      secret_handshake.go

22
secret_handshake.go

@ -13,31 +13,29 @@ const (
// Handshake receives an integer argument and returns a string slice with
// the code words in the proper sequence.
func Handshake(i int) (h []string) {
m := map[int]string{
wnk: "wink",
bli: "double blink",
clo: "close your eyes",
jmp: "jump",
}
// Store the handshake phrases in a string slice (maps are slow).
s := []string{"wink", "double blink", "close your eyes", "jump"}
// Return the original empty slice if the integer is negative.
// Return the original nil slice if the integer is negative.
if i < 0 {
return h
}
// Build the slice by bitmasking the integer.
if i&wnk != 0 {
h = append(h, m[wnk])
h = append(h, s[0])
}
if i&bli != 0 {
h = append(h, m[bli])
h = append(h, s[1])
}
if i&clo != 0 {
h = append(h, m[clo])
h = append(h, s[2])
}
if i&jmp != 0 {
h = append(h, m[jmp])
h = append(h, s[3])
}
// Reverse the slice if the 5th bit is set.
if i&rev != 0 {
for i, j := 0, len(h)-1; i < j; i, j = i+1, j-1 {
h[i], h[j] = h[j], h[i]
@ -50,4 +48,4 @@ func Handshake(i int) (h []string) {
// Revision 1 benchmark:
//
// PASS
// BenchmarkHandshake-12 2000000 734 ns/op
// BenchmarkHandshake-12 5000000 334 ns/op
Loading…
Cancel
Save