perf: less alloc (#25360)

Co-authored-by: Alex | Interchain Labs <alex@cosmoslabs.io>
This commit is contained in:
cui 2025-10-16 05:37:22 +08:00 committed by GitHub
parent b578aa71cb
commit ce8bed2fd5
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 55 additions and 5 deletions

View File

@ -224,11 +224,9 @@ func loadPruningSnapshotHeights(db dbm.DB) ([]int64, error) {
}
func int64SliceToBytes(slice ...int64) []byte {
bz := make([]byte, 0, len(slice)*8)
for _, ph := range slice {
buf := make([]byte, 8)
binary.BigEndian.PutUint64(buf, uint64(ph))
bz = append(bz, buf...)
bz := make([]byte, len(slice)*8)
for i, ph := range slice {
binary.BigEndian.PutUint64(bz[i<<3:], uint64(ph))
}
return bz
}

View File

@ -1,6 +1,7 @@
package pruning
import (
"encoding/binary"
"errors"
"fmt"
"testing"
@ -454,3 +455,54 @@ func TestLoadSnapshotHeights_PruneNothing(t *testing.T) {
require.Nil(t, manager.LoadSnapshotHeights(db.NewMemDB()))
}
func TestInt64SliceToBytes(t *testing.T) {
tests := []struct {
name string
input []int64
expect []byte
}{
{
name: "empty slice",
input: []int64{},
expect: []byte{},
},
{
name: "single value",
input: []int64{1},
expect: func() []byte {
b := make([]byte, 8)
binary.BigEndian.PutUint64(b, 1)
return b
}(),
},
{
name: "multiple values",
input: []int64{1, 2},
expect: func() []byte {
b := make([]byte, 16)
binary.BigEndian.PutUint64(b[0:], 1)
binary.BigEndian.PutUint64(b[8:], 2)
return b
}(),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := int64SliceToBytes(tt.input...)
require.Equal(t, tt.expect, got, "bytes mismatch")
})
}
}
func BenchmarkInt64SliceToBytes(b *testing.B) {
data := make([]int64, 1024)
for i := range data {
data[i] = int64(i)
}
for b.Loop() {
_ = int64SliceToBytes(data...)
}
}