all: pre-allocate memory for slices and maps, close XFN-148 (#1714)

This commit is contained in:
Daniel Liu 2025-11-14 22:43:36 +08:00 committed by GitHub
parent f65ecda9f1
commit eef5242fa3
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
26 changed files with 33 additions and 37 deletions

View file

@ -276,7 +276,7 @@ func parseLibraryDeps(unlinkedCode string) (res []string) {
// onItem on each. If the callback returns an error, iteration is halted and
// the error is returned from iterSorted.
func iterSorted[V any](inp map[string]V, onItem func(string, V) error) error {
var sortedKeys []string
sortedKeys := make([]string, 0, len(inp))
for key := range inp {
sortedKeys = append(sortedKeys, key)
}

View file

@ -62,7 +62,7 @@ func (argument *Argument) UnmarshalJSON(data []byte) error {
// NonIndexed returns the arguments with indexed arguments filtered out.
func (arguments Arguments) NonIndexed() Arguments {
var ret []Argument
ret := make([]Argument, 0, len(arguments))
for _, arg := range arguments {
if !arg.Indexed {
ret = append(ret, arg)

View file

@ -41,7 +41,7 @@ import (
// mutations to the binding code.
func TestBindingGeneration(t *testing.T) {
matches, _ := filepath.Glob("internal/contracts/*")
var dirs []string
dirs := make([]string, 0, len(matches))
for _, match := range matches {
f, _ := os.Stat(match)
if f.IsDir() {
@ -50,12 +50,6 @@ func TestBindingGeneration(t *testing.T) {
}
for _, dir := range dirs {
var (
abis []string
bins []string
types []string
libs = make(map[string]string)
)
basePath := filepath.Join("internal/contracts", dir)
combinedJsonPath := filepath.Join(basePath, "combined-abi.json")
abiBytes, err := os.ReadFile(combinedJsonPath)
@ -67,6 +61,10 @@ func TestBindingGeneration(t *testing.T) {
t.Fatalf("Failed to read contract information from json output: %v", err)
}
abis := make([]string, 0, len(contracts))
bins := make([]string, 0, len(contracts))
types := make([]string, 0, len(contracts))
libs := make(map[string]string, len(contracts))
for name, contract := range contracts {
// fully qualified name is of the form <solFilePath>:<type>
nameParts := strings.Split(name, ":")

View file

@ -45,9 +45,7 @@ func TestPack(t *testing.T) {
if err != nil {
t.Fatalf("invalid ABI definition %s, %v", inDef, err)
}
var packed []byte
packed, err = inAbi.Pack("method", test.unpacked)
packed, err := inAbi.Pack("method", test.unpacked)
if err != nil {
t.Fatalf("test %d (%v) failed: %v", i, test.def, err)
}

View file

@ -65,7 +65,7 @@ type Manager struct {
// supported backends.
func NewManager(config *Config, backends ...Backend) *Manager {
// Retrieve the initial list of wallets from the backends and sort by URL
var wallets []Wallet
wallets := make([]Wallet, 0, len(backends))
for _, backend := range backends {
wallets = merge(wallets, backend.Wallets()...)
}

View file

@ -218,7 +218,7 @@ func (t *Tree) Draw(hash []byte, d int) string {
hashes = append(hashes, []string{"", fmt.Sprintf("%v", hashstr(hash)), ""})
total := 60
del := " "
var rows []string
rows := make([]string, 0, len(hashes)+2)
for i := len(hashes) - 1; i >= 0; i-- {
var textlen int
hash := hashes[i]

View file

@ -229,7 +229,7 @@ func makeFullNode(ctx *cli.Context) (*node.Node, ethapi.Backend, XDCConfig) {
// Create gauge with geth system and build information
if eth != nil { // The 'eth' backend may be nil in light mode
var protos []string
protos := make([]string, 0, len(eth.Protocols()))
for _, p := range eth.Protocols() {
protos = append(protos, fmt.Sprintf("%v/%d", p.Name, p.Version))
}

View file

@ -218,8 +218,8 @@ func (x *XDPoS) VerifyHeaders(chain consensus.ChainReader, headers []*types.Head
// Split the headers list into v1 and v2 buckets
var v1headers []*types.Header
var v2headers []*types.Header
var v1fullVerifies []bool
var v2fullVerifies []bool
v1fullVerifies := make([]bool, 0, len(headers))
v2fullVerifies := make([]bool, 0, len(headers))
for i, header := range headers {
switch x.config.BlockConsensusVersion(header.Number) {

View file

@ -274,7 +274,7 @@ func (f *Forensics) findQCsInSameRound(quorumCerts1 []types.QuorumCert, quorumCe
// Find the signer list from QC signatures
func (f *Forensics) getQcSignerAddresses(quorumCert types.QuorumCert) []string {
var signerList []string
signerList := make([]string, 0, len(quorumCert.Signatures))
// The QC signatures are signed by votes special struct VoteForSign
quorumCertSignedHash := types.VoteSigHash(&types.VoteForSign{

View file

@ -74,7 +74,7 @@ func (p *Pool) PoolObjKeysList() []string {
p.lock.RLock()
defer p.lock.RUnlock()
var keyList []string
keyList := make([]string, 0, len(p.objList))
for key := range p.objList {
keyList = append(keyList, key)
}

View file

@ -38,8 +38,8 @@ func ExtractValidatorsFromBytes(byteValidators []byte) ([]int64, error) {
return []int64{}, fmt.Errorf("invalid byte array length %d for validators", len(byteValidators))
}
lenValidator := len(byteValidators) / M2ByteLength
var validators []int64
for i := 0; i < lenValidator; i++ {
validators := make([]int64, 0, lenValidator)
for i := range lenValidator {
trimByte := bytes.Trim(byteValidators[i*M2ByteLength:(i+1)*M2ByteLength], "\x00")
intNumber, err := strconv.ParseInt(string(trimByte), 10, 64)
if err != nil {

View file

@ -261,7 +261,7 @@ func (c *Console) clearHistory() {
// consoleOutput is an override for the console.log and console.error methods to
// stream the output into the configured output stream instead of stdout.
func (c *Console) consoleOutput(call goja.FunctionCall) goja.Value {
var output []string
output := make([]string, 0, len(call.Arguments))
for _, argument := range call.Arguments {
output = append(output, fmt.Sprintf("%v", argument))
}

View file

@ -275,7 +275,7 @@ func GenM2FromRandomize(randomizes []int64, lenSigners int64) ([]int64, error) {
// Get validators from m2 array integer.
func BuildValidatorFromM2(listM2 []int64) []byte {
var validatorBytes []byte
validatorBytes := make([]byte, 0, len(listM2)*utils.M2ByteLength)
for _, numberM2 := range listM2 {
// Convert number to byte.
m2Byte := common.LeftPadBytes(fmt.Appendf(nil, "%d", numberM2), utils.M2ByteLength)

View file

@ -166,7 +166,7 @@ func isArrayEqual(a [][]int64, b [][]int64) bool {
// Unit test for
func TestGenM2FromRandomize(t *testing.T) {
var a []int64
a := make([]int64, 0, 11)
for i := 0; i <= 10; i++ {
a = append(a, int64(rand.Intn(9999)))
}

View file

@ -24,7 +24,7 @@ import (
func lexAll(src string) []token {
ch := Lex("test.asm", []byte(src), false)
var tokens []token
tokens := make([]token, 0, len(ch))
for i := range ch {
tokens = append(tokens, i)
}

View file

@ -39,7 +39,7 @@ type freezerdb struct {
// Close implements io.Closer, closing both the fast key-value store as well as
// the slow ancient tables.
func (frdb *freezerdb) Close() error {
var errs []error
errs := make([]error, 0, 2)
if err := frdb.AncientStore.Close(); err != nil {
errs = append(errs, err)
}

View file

@ -356,7 +356,7 @@ func newTestAction(addr common.Address, r *rand.Rand) testAction {
},
}
action := actions[r.Intn(len(actions))]
var nameargs []string
nameargs := make([]string, 0, 1+len(action.args))
if !action.noAddr {
nameargs = append(nameargs, addr.Hex())
}

View file

@ -68,7 +68,7 @@ func NewStateProcessor(config *params.ChainConfig, bc *BlockChain, engine consen
// transactions failed to execute due to insufficient gas it will return an error.
func (p *StateProcessor) Process(block *types.Block, statedb *state.StateDB, tradingState *tradingstate.TradingStateDB, cfg vm.Config, tokensFee map[common.Address]*big.Int) (types.Receipts, []*types.Log, uint64, error) {
var (
receipts types.Receipts
receipts = make([]*types.Receipt, 0, len(block.Transactions()))
usedGas = new(uint64)
header = block.Header()
blockHash = block.Hash()

View file

@ -92,7 +92,7 @@ func DeriveSha(list DerivableList, hasher TrieHasher) common.Hash {
// StackTrie requires values to be inserted in increasing hash order, which is not the
// order that `list` provides hashes in. This insertion sequence ensures that the
// order is correct.
var indexBuf []byte
indexBuf := make([]byte, 0, list.Len())
for i := 1; i < list.Len() && i <= 0x7f; i++ {
indexBuf = rlp.AppendUint64(indexBuf[:0], uint64(i))
value := encodeForDerive(list, i, valueBuf)

View file

@ -608,7 +608,7 @@ func (s Transactions) EncodeIndex(i int, w *bytes.Buffer) {
func TxDifference(a, b Transactions) (keep Transactions) {
keep = make(Transactions, 0, len(a))
remove := make(map[common.Hash]struct{})
remove := make(map[common.Hash]struct{}, len(b))
for _, tx := range b {
remove[tx.Hash()] = struct{}{}
}
@ -626,7 +626,7 @@ func TxDifference(a, b Transactions) (keep Transactions) {
func HashDifference(a, b []common.Hash) []common.Hash {
keep := make([]common.Hash, 0, len(a))
remove := make(map[common.Hash]struct{})
remove := make(map[common.Hash]struct{}, len(b))
for _, hash := range b {
remove[hash] = struct{}{}
}

View file

@ -127,11 +127,11 @@ func NewEVMInterpreter(evm *EVM) *EVMInterpreter {
default:
table = &frontierInstructionSet
}
var extraEips []int
if len(evm.Config.ExtraEips) > 0 {
// Deep-copy jumptable to prevent modification of opcodes in other tables
table = copyJumpTable(table)
}
extraEips := make([]int, 0, len(evm.Config.ExtraEips))
for _, eip := range evm.Config.ExtraEips {
if err := EnableEIP(eip, table); err != nil {
// Disable it, so caller can check if it's activated or not

View file

@ -85,7 +85,7 @@ func HashFolder(folder string, exlude []string) (map[string][32]byte, error) {
// DiffHashes compares two maps of file hashes and returns the changed files.
func DiffHashes(a map[string][32]byte, b map[string][32]byte) []string {
var updates []string
updates := make([]string, 0, len(a)+len(b))
for file := range a {
if _, ok := b[file]; !ok || a[file] != b[file] {

View file

@ -140,7 +140,7 @@ func (c *collector) writeGaugeInfo(name string, value metrics.GaugeInfoValue) {
c.buff.WriteString(fmt.Sprintf(typeGaugeTpl, name))
c.buff.WriteString(name)
c.buff.WriteString(" ")
var kvs []string
kvs := make([]string, 0, len(value))
for k, v := range value {
kvs = append(kvs, fmt.Sprintf("%v=%q", k, v))
}

View file

@ -49,8 +49,8 @@ type orderedRegistry struct {
// Each call the given function for each registered metric.
func (r *orderedRegistry) Each(f func(string, interface{})) {
var names []string
reg := r.registered()
names := make([]string, 0, len(reg))
for name := range reg {
names = append(names, name)
}

View file

@ -179,7 +179,7 @@ func (h *httpServer) start() error {
)
// Log all handlers mounted on server.
var paths []string
paths := make([]string, 0, len(h.handlerNames))
for path := range h.handlerNames {
paths = append(paths, path)
}

View file

@ -384,7 +384,7 @@ func TestDuplicateAvoidanceSync(t *testing.T) {
// The code requests are ignored here since there is no code
// at the testing trie.
paths, nodes, _ := sched.Missing(0)
var elements []trieElement
elements := make([]trieElement, 0, len(paths))
for i := 0; i < len(paths); i++ {
elements = append(elements, trieElement{
path: paths[i],