Skip to content

Commit 639cd65

Browse files
committed
Better coloring performance
This allows the compiler to inline the ANSI codes and to save 2 bytes/op, reduucing the perf at 7 bytes/op instead of 9 bytes/op. Knowing that the original code only uses 3 bytes/op, there is still space for improvement
1 parent f372d4c commit 639cd65

File tree

2 files changed

+43
-8
lines changed

2 files changed

+43
-8
lines changed

assert/colors.go

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,22 +7,24 @@ import (
77
"golang.org/x/term"
88
)
99

10-
const redMark = "\033[0;31m"
11-
const greenMark = "\033[0;32m"
12-
const endMark = "\033[0m"
10+
const (
11+
redMark = "\033[0;31m"
12+
greenMark = "\033[0;32m"
13+
endMark = "\033[0m"
14+
)
15+
16+
var isTerminal = term.IsTerminal(int(os.Stdout.Fd()))
1317

1418
func redColored(i interface{}) interface{} {
1519
if isTerminal {
16-
return redMark + fmt.Sprintf("%s", i) + endMark
20+
return fmt.Sprintf(redMark+"%s"+endMark, i)
1721
}
1822
return i
1923
}
2024

2125
func greenColored(i interface{}) interface{} {
2226
if isTerminal {
23-
return greenMark + fmt.Sprintf("%s", i) + endMark
27+
return fmt.Sprintf(greenMark+"%s"+endMark, i)
2428
}
2529
return i
2630
}
27-
28-
var isTerminal = term.IsTerminal(int(os.Stdout.Fd()))

assert/colors_test.go

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
package assert
22

3-
import "testing"
3+
import (
4+
"fmt"
5+
"testing"
6+
)
47

58
func BenchmarkColored(b *testing.B) {
69
b.Run("benchMarkingString", func(b *testing.B) {
@@ -18,3 +21,33 @@ func BenchmarkColored(b *testing.B) {
1821
}
1922
})
2023
}
24+
25+
// Not benchmarking `Equal` but the string formatting
26+
// because it will make the benchmark fail.
27+
func BenchmarkEqual(b *testing.B) {
28+
29+
s := struct {
30+
a int
31+
b string
32+
}{3, "helloWorld"}
33+
34+
b.Run("Base", func(b *testing.B) {
35+
36+
for i := 0; i < b.N; i++ {
37+
_ = fmt.Sprintf("Not equal: \n"+
38+
"expected: %v\n"+
39+
"actual : %v%s", s, s, "")
40+
}
41+
})
42+
43+
b.Run("Colored (test with and without terminal)", func(b *testing.B) {
44+
// This benchmark give very different results whether the output is a terminal or not.
45+
46+
for i := 0; i < b.N; i++ {
47+
_ = fmt.Sprintf("Not equal: \n"+
48+
"expected: %s\n"+
49+
"actual : %s%s", greenColored(s), redColored(s), "")
50+
}
51+
})
52+
53+
}

0 commit comments

Comments
 (0)