4
Using the make([]byte, tamanho)
he has a different behavior when the 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 tamanho
, of 1024. The only difference is that the first is constant (it also has the same effect if using make([]byte, 1024)
directly), but the second case is slower than the first.
Using the first shape can be five times faster than using a variable. Now, why is this? Because using a variable value can have a difference so great?
I believe they’re both fast enough, but what’s strange is there’s such a difference to 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 checks if the value is less than zero, it 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?
What are these numbers that precede the times?
– Jefferson Quesado
The numbers indicate the amount of iterations and the time it took for each, at least the information in the manual.
– Inkeliz
I believe the assumption is correct :) Constancy works miracles...
– Maniero