Using make([]byte, tamanho)
it behaves differently when tamanho
is a variable or a constant.
Consider the two codes:
package Testes
import (
"testing"
)
func BenchmarkConstante(b *testing.B) {
const tamanho = 1024
for n := 0; n < b.N; n++ {
_ = make([]byte, tamanho)
}
}
func BenchmarkVariavel(b *testing.B) {
var tamanho = 1024
for n := 0; n < b.N; n++ {
_ = make([]byte, tamanho)
}
}
The only difference between the two is
const
andvar
.
They return:
50000000 35.5 ns/op
10000000 181 ns/op
Both have the same% w / o of 1024. The only difference is that the first is constant (it also has the same effect if you use tamanho
directly), but the second case is slower than the first.
Using the first form can be five times faster than using a variable. Now, why does this occur? Why use a variable value can have a difference so large ?
I think both are fast enough, but what's strange is that there's such a difference for something so simple.
My guess is that the compiler can reduce something when using a constant value. Meanwhile, using a variable would add some other checks, for example check if the value is less than zero, this does not need to use a constant value, since this is done at the time it compiles.
I think it might be something like this, but what exactly would it be?