Skip to content

Commit

Permalink
base 64 Id generator
Browse files Browse the repository at this point in the history
* < 50% allocations

BenchmarkUint64ToId-8        	50000000	        30.6 ns/op	       7 B/op	       1 allocs/op
BenchmarkUint64ToString2-8   	20000000	       125 ns/op	      63 B/op	       2 allocs/op
  • Loading branch information
stuartcarnie committed Dec 23, 2016
1 parent bb76b0b commit 2ca7813
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 3 deletions.
25 changes: 22 additions & 3 deletions actor/process_registry.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package actor

import (
"strconv"
"sync/atomic"

cmap "github.com/orcaman/concurrent-map"
Expand All @@ -26,13 +25,33 @@ type HostResolver func(*PID) (ActorRef, bool)

func (pr *ProcessRegistryValue) RegisterHostResolver(handler HostResolver) {
pr.RemoteHandlers = append(pr.RemoteHandlers, handler)
}

const (
digits = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~+"
)

func uint64ToId(u uint64) string {
var buf [13]byte
i := 13
// base is power of 2: use shifts and masks instead of / and %
for u >= 64 {
i--
buf[i] = digits[uintptr(u)&0x3f]
u >>= 6
}
// u < base
i--
buf[i] = digits[uintptr(u)]
i--
buf[i] = '$'

return string(buf[i:])
}

func (pr *ProcessRegistryValue) getAutoId() string {
counter := atomic.AddUint64(&pr.SequenceID, 1)
id := "$" + strconv.FormatUint(counter, 16)
return id
return uint64ToId(counter)
}

func (pr *ProcessRegistryValue) add(actorRef ActorRef, id string) (*PID, bool) {
Expand Down
47 changes: 47 additions & 0 deletions actor/process_registry_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package actor

import (
"strconv"
"testing"

"github.com/stretchr/testify/assert"
)

func TestUint64ToId(t *testing.T) {
cases := []struct {
i uint64
e string
}{
{0xfedcba9876543210, "$fXsKFxSl38g"},
{0x0, "$0"},
{0x1, "$1"},
{0xf, "$f"},
{0x1041041041041041, "$11111111111"},
}
for _, tc := range cases {
t.Run(tc.e, func(t *testing.T) {
s := uint64ToId(tc.i)
assert.Equal(t, tc.e, s)
})
}

}

var ss string

func BenchmarkUint64ToId(b *testing.B) {
var s string
for i := 0; i < b.N; i++ {
s = uint64ToId(uint64(i)<<5)
}
ss = s
}

func BenchmarkUint64ToString2(b *testing.B) {
var s string
var buf [12]byte
for i := 0; i < b.N; i++ {
s = string(strconv.AppendUint(buf[:], uint64(i)<<5, 36))
}
ss = s
}

0 comments on commit 2ca7813

Please sign in to comment.