Boxing bytes is faster than boxing integers within [0. 255]. Why?

180 views
Skip to first unread message

tapi...@gmail.com

unread,
May 10, 2021, 10:29:50 AM5/10/21
to golang-nuts
Different optimizations are applied for them?

The benchmark:

package main

import "testing"

func BoxByte(b byte) interface{} {
    return b
}

func BoxInt64(i int64) interface{} {
    return i
}

var b0, b1, b2 byte = 0, 128, 255
var d, e, f interface{}
func Benchmark_BoxByte(b *testing.B) {
    for i := 0; i < b.N; i++ {
        d = BoxByte(b0)
        e = BoxByte(b1)
        f = BoxByte(b2)
    }
}

var i0s, i1s, i2s int64 = 0, 128, 255
var m, n, o interface{}
func Benchmark_BoxInt64_Small(b *testing.B) {
    for i := 0; i < b.N; i++ {
        m = BoxInt64(i0s)
        n = BoxInt64(i1s)
        o = BoxInt64(i2s)
    }
}

var i0b, i1b, i2b int64 = 256, 1024, 65536
var x, y, z interface{}
func Benchmark_BoxInt64_Large(b *testing.B) {
    for i := 0; i < b.N; i++ {
        x = BoxInt64(i0b)
        y = BoxInt64(i1b)
        z = BoxInt64(i2b)
    }
}

The result:

$ go test -bench=.
goos: linux
goarch: amd64
pkg: a.b/c/ttt
cpu: Intel(R) Core(TM) i5-4210U CPU @ 1.70GHz
Benchmark_BoxByte-4              429777054             2.681 ns/op
Benchmark_BoxInt64_Small-4       125588462             9.527 ns/op
Benchmark_BoxInt64_Large-4       18019028            63.75 ns/op


Jan Mercl

unread,
May 10, 2021, 10:38:39 AM5/10/21
to tapi...@gmail.com, golang-nuts

tapi...@gmail.com

unread,
May 10, 2021, 10:45:30 AM5/10/21
to golang-nuts
Yes, I'm aware of this optimization.
But it looks another optimization is applied for boxing bytes.

Axel Wagner

unread,
May 10, 2021, 11:40:07 AM5/10/21
to tapi...@gmail.com, golang-nuts

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/1b5feb93-a1b9-4bd7-871a-d4851c15f031n%40googlegroups.com.

tapi...@gmail.com

unread,
May 10, 2021, 12:51:49 PM5/10/21
to golang-nuts
I'm not familiar with the compile code, but I guess it should be helpful.
It looks boxing bytes are handled at compile time but boxing small integers are handled at run time.

Thanks for the info.

Axel Wagner

unread,
May 10, 2021, 2:07:56 PM5/10/21
to tapi...@gmail.com, golang-nuts
Yes, as a `byte` is statically known to be less than 256, while a larger integer type is not.

Reply all
Reply to author
Forward
0 new messages