Skip to content

Commit

Permalink
Merge pull request #1 from Pincheng0101/optimize
Browse files Browse the repository at this point in the history
Optimize DecodeString performance and memory usage
  • Loading branch information
yetisno authored Apr 8, 2022
2 parents edb9aba + 4d94409 commit d62f01a
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 9 deletions.
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

0 comments on commit d62f01a

Please sign in to comment.