Skip to content

Commit

Permalink
[FEAT] Avoid compiler optimization in benchmarks
Browse files Browse the repository at this point in the history
The addition of a global variable does not allow
the compiler to carry out optimization behind the
scene, which can affect the comparison of this
implementation with other ones.
  • Loading branch information
mdm-code committed Oct 28, 2022
1 parent 971d891 commit 8531091
Showing 1 changed file with 8 additions and 1 deletion.
9 changes: 8 additions & 1 deletion termcols_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,23 @@ import (
"testing"
)

// NOTE: benchResult is added to avoid compiler optimization
var (
benchResult string
)

// BenchmarkColorize was arranged to test the performance of the slice type
// conversion using unsafe.Pointer as opposed to looping over the source
// slice and appending elements one after another to the target slice.
//
// In my testing slice type conversion with unsafe.Pointer is almost four
// times faster than the memory-safe alternative.
func BenchmarkColorize(b *testing.B) {
var s string
for i := 0; i < b.N; i++ {
Colorize("Colorize me!", BlackFg)
s = Colorize("Colorize me!", BlackFg)
}
benchResult = s
}

func TestColorize(t *testing.T) {
Expand Down

0 comments on commit 8531091

Please sign in to comment.