Skip to content

Commit

Permalink
common/hexutil: improve performance of EncodeBig (ethereum#23780)
Browse files Browse the repository at this point in the history
- use Text instead of fmt.Sprintf
- reduced allocs from 6 to 2
- improved speed
  • Loading branch information
lmittmann authored and gzliudan committed Dec 28, 2024
1 parent 4db72a0 commit 49dc5e8
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
11 changes: 6 additions & 5 deletions common/hexutil/hexutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
Package hexutil implements hex encoding with 0x prefix.
This encoding is used by the Ethereum RPC API to transport binary data in JSON payloads.
Encoding Rules
# Encoding Rules
All hex data must have prefix "0x".
Expand Down Expand Up @@ -175,13 +175,14 @@ func MustDecodeBig(input string) *big.Int {
}

// EncodeBig encodes bigint as a hex string with 0x prefix.
// The sign of the integer is ignored.
func EncodeBig(bigint *big.Int) string {
nbits := bigint.BitLen()
if nbits == 0 {
if sign := bigint.Sign(); sign == 0 {
return "0x0"
} else if sign > 0 {
return "0x" + bigint.Text(16)
} else {
return "-0x" + bigint.Text(16)[1:]
}
return fmt.Sprintf("%#x", bigint)
}

func has0xPrefix(input string) bool {
Expand Down
12 changes: 12 additions & 0 deletions common/hexutil/hexutil_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -201,3 +201,15 @@ func TestDecodeUint64(t *testing.T) {
}
}
}

func BenchmarkEncodeBig(b *testing.B) {
for _, bench := range encodeBigTests {
b.Run(bench.want, func(b *testing.B) {
b.ReportAllocs()
bigint := bench.input.(*big.Int)
for i := 0; i < b.N; i++ {
EncodeBig(bigint)
}
})
}
}

0 comments on commit 49dc5e8

Please sign in to comment.