github.com/bananabytelabs/wazero@v0.0.0-20240105073314-54b22a776da8/internal/integration_test/bench/interface_bench_test.go (about) 1 package bench 2 3 import ( 4 "encoding/binary" 5 "testing" 6 ) 7 8 func BenchmarkInterfaceVSUnexport(b *testing.B) { 9 const size = 100 10 const val = 55 11 var memInterface MemoryInstanceInterface = &memoryInstance{buffer: make([]byte, size)} 12 memStruct := &memoryInstance{buffer: make([]byte, size)} 13 14 b.Run("interface", func(b *testing.B) { 15 for i := 0; i < b.N; i++ { 16 for addr := uint32(0); addr < size+1000; addr++ { 17 memInterface.PutUint32(addr, val) 18 } 19 } 20 }) 21 b.Run("struct", func(b *testing.B) { 22 for i := 0; i < b.N; i++ { 23 for addr := uint32(0); addr < size+1000; addr++ { 24 memStruct.PutUint32(addr, val) 25 } 26 } 27 }) 28 } 29 30 type MemoryInstanceInterface interface { 31 PutUint32(addr uint32, val uint32) bool 32 } 33 34 type memoryInstance struct { 35 buffer []byte // inexpert only this 36 Min uint32 // PS especially below would make sense to also not export as export makes it mutable 37 Max *uint32 38 } 39 40 func (m *memoryInstance) validateAddrRange(addr uint32, rangeSize uint64) bool { 41 return uint64(addr) < uint64(len(m.buffer)) && rangeSize <= uint64(len(m.buffer))-uint64(addr) 42 } 43 44 func (m *memoryInstance) PutUint32(addr uint32, val uint32) bool { 45 if !m.validateAddrRange(addr, uint64(4)) { 46 return false 47 } 48 binary.LittleEndian.PutUint32(m.buffer[addr:], val) 49 return true 50 }