Skip to content

Commit

Permalink
Decode: use unsafe []byte->string conversion for discarded value
Browse files Browse the repository at this point in the history
For Decode's MLI4I, we invoke strconv.Atoi after string(*b)
which incurs a []byte->string allocation. The converted []byte->string
is discarded so anyways it is okay to use unsafe, as the string is
never used again.

Results:

* time/op (ns/op)
Encoding/Decoding_2I-8	7.5ns ± 1%  6.7ns ± 0%  -10.36%	(p=0.000 n=10+9)
Encoding/Decoding_4E-8	8.8ns ± 0%  7.9ns ± 0%  -10.35%	(p=0.000 n=10+10)
Encoding/Decoding_A4E-8	38ns ± 1%   17ns ± 0%   -54.84%	(p=0.000 n=10+10)

* allocs/op (B/op)
Encoding/Decoding_A4E-8	4.0B ± 0%   0	-100.00% (p=0.000 n=10+10)

* allocs/op (N/op)
Encoding/Decoding_A4E-8	1.0 ± 0%    0	-100.00% (p=0.000 n=10+10)
  • Loading branch information
odeke-em committed Sep 25, 2021
1 parent 3a0b64d commit 7453e32
Showing 1 changed file with 6 additions and 1 deletion.
7 changes: 6 additions & 1 deletion mli.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ import (
"encoding/hex"
"fmt"
"strconv"
"unsafe"
)

// empty is used as a quick return during errors
Expand Down Expand Up @@ -238,7 +239,7 @@ func Decode(key string, b *[]byte) (int, error) {
}

// Convert to integer from ASCII
n, err := strconv.Atoi(string(*b))
n, err := strconv.Atoi(unsafeByteToStr(*b))
if err != nil {
return 0, fmt.Errorf("unable to convert string values to integer - %s", err)
}
Expand All @@ -249,6 +250,10 @@ func Decode(key string, b *[]byte) (int, error) {
}
}

func unsafeByteToStr(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
}

// Encode will accept a message length type and message length value desired. Encode will return a byte slice which
// contains a MLI formatted for in the desired message length type.
//
Expand Down

0 comments on commit 7453e32

Please sign in to comment.