Skip to content

Commit 2954f40

Browse files
authored
common/hexutil: improve performance of EncodeBig (#23780)
- use Text instead of fmt.Sprintf - reduced allocs from 6 to 2 - improved speed
1 parent b6fb184 commit 2954f40

File tree

2 files changed

+17
-4
lines changed

2 files changed

+17
-4
lines changed

common/hexutil/hexutil.go

+5-4
Original file line numberDiff line numberDiff line change
@@ -176,13 +176,14 @@ func MustDecodeBig(input string) *big.Int {
176176
}
177177

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

188189
func has0xPrefix(input string) bool {

common/hexutil/hexutil_test.go

+12
Original file line numberDiff line numberDiff line change
@@ -201,3 +201,15 @@ func TestDecodeUint64(t *testing.T) {
201201
}
202202
}
203203
}
204+
205+
func BenchmarkEncodeBig(b *testing.B) {
206+
for _, bench := range encodeBigTests {
207+
b.Run(bench.want, func(b *testing.B) {
208+
b.ReportAllocs()
209+
bigint := bench.input.(*big.Int)
210+
for i := 0; i < b.N; i++ {
211+
EncodeBig(bigint)
212+
}
213+
})
214+
}
215+
}

0 commit comments

Comments
 (0)