Skip to content

Conversation

cuiweixie
Copy link
Contributor

test and bench:

package main

import (
	"bytes"
	"testing"

	"github.com/ethereum/go-ethereum/common"
	"github.com/holiman/uint256"
)

func incHash(h common.Hash) common.Hash {
	var a uint256.Int
	a.SetBytes32(h[:])
	a.AddUint64(&a, 1)
	return common.Hash(a.Bytes32())
}

func incHashFast(h common.Hash) common.Hash {
	for i := len(h) - 1; i >= 0; i-- {
		h[i]++
		if h[i] != 0 {
			break
		}
	}
	return h
}

func TestIncHashCorrectness(t *testing.T) {
	testCases := []common.Hash{
		common.HexToHash("0x0"),
		common.HexToHash("0x01"),
		common.HexToHash("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"), // 最大值
		common.HexToHash("0x00000000000000000000000000000000000000000000000000000000ffffffff"), // 边界
	}

	for _, tc := range testCases {
		got1 := incHash(tc)
		got2 := incHashFast(tc)

		if !bytes.Equal(got1[:], got2[:]) {
			t.Errorf("Mismatch for %x: uint256=%x fast=%x", tc, got1, got2)
		}
	}
}

// Benchmark origin
func BenchmarkIncHash(b *testing.B) {
	var h common.Hash
	for i := 0; i < b.N; i++ {
		_ = incHash(h)
	}
}

// Benchmark optimized
func BenchmarkIncHashFast(b *testing.B) {
	var h common.Hash
	for i := 0; i < b.N; i++ {
		_ = incHashFast(h)
	}
}

goos: darwin
goarch: arm64
pkg: github.com/cuiweixie/mylabs/tests/inc_hash
cpu: Apple M1 Pro
BenchmarkIncHash
BenchmarkIncHash-10        	175488444	         6.941 ns/op
BenchmarkIncHashFast
BenchmarkIncHashFast-10    	1000000000	         0.8142 ns/op
PASS

@rjl493456442 rjl493456442 self-assigned this Sep 26, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants