Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize DecodeString performance and memory usage #1

Merged
merged 1 commit into from
Apr 8, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 8 additions & 9 deletions base62.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ const (
encodeStd = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
)


var baseInt = 62
var base = big.NewInt(int64(baseInt))
var StdEncoding = NewEncoding(encodeStd)
Expand Down Expand Up @@ -102,15 +101,13 @@ func (enc *Encoding) doEncode(num *big.Int, shift int) *strings.Builder {
builder.WriteByte(enc.encode[shift])
}

for ; num.Int64() != 0; {
for num.Int64() != 0 {
mod := enc.encode[new(big.Int).Mod(num, base).Int64()]
num = num.Div(num, base)
builder.WriteByte(mod)
}

if !enc.forward {
return builder
} else {
if enc.forward {
rtn := new(strings.Builder)
bs := builder.String()
l := len(bs)
Expand All @@ -122,6 +119,8 @@ func (enc *Encoding) doEncode(num *big.Int, shift int) *strings.Builder {
rtn.Write(rd)
return rtn
}

return builder
}

func (enc *Encoding) DecodeString(s string) []byte {
Expand All @@ -130,13 +129,13 @@ func (enc *Encoding) DecodeString(s string) []byte {
}

if enc.forward {
bs := []byte(s)
l := len(s)
d := ""
for i := 0; i < l; i++ {
d += string(s[l-i-1])
for i := 0; i < l/2; i++ {
bs[i], bs[l-i-1] = bs[l-i-1], bs[i]
}

s = d
s = string(bs)
}

shift := 0
Expand Down
10 changes: 10 additions & 0 deletions base62_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,16 @@ func TestBase62(t *testing.T) {
wg.Wait()
}

func BenchmarkBase62(b *testing.B) {
for i := 0; i < b.N; i++ {
d := []byte(random(i))
StdEncoding.DecodeString(StdEncoding.EncodeToString(d))
FlipEncoding.DecodeString(FlipEncoding.EncodeToString(d))
ShiftEncoding.DecodeString(ShiftEncoding.EncodeToString(d))
FlipShiftEncoding.DecodeString(FlipShiftEncoding.EncodeToString(d))
}
}

func random(l int) string {
rand.Seed(time.Now().UnixNano())
chars := []rune("ABCDEFGHIJKLMNOPQRSTUVWXYZÅÄÖ" +
Expand Down