Go Optimizations 101 (20240316) by Tapir Liu

Go Optimizations 101 (20240316) by Tapir Liu

Author:Tapir Liu
Language: eng
Format: epub


Small-size structs are optimized specially

This has been talked about in value copy costs and small-size types/values.

Make struct size smaller by adjusting field orders

Struct field orders might affect struct sizes, which has been mentioned in a previous chapter.

Arrays and Slices

Avoid using literals of large-size array types as comparison operands

For example, in the following code, the function CompareWithGlobalVar is more performant than the function CompareWithLiteral (for the official standard Go compiler v1.22.n).

package arrays import "testing" type T [1000]byte var zero = T{} func CompareWithLiteral(t *T) bool { return *t == T{} } func CompareWithGlobalVar(t *T) bool { return *t == zero } var x T var r bool func Benchmark_CompareWithLiteral(b *testing.B) { for i := 0; i < b.N; i++ { r = CompareWithLiteral(&x) } } func Benchmark_CompareWithGlobalVar(b *testing.B) { for i := 0; i < b.N; i++ { r = CompareWithGlobalVar(&x) } }

The benchmark results:

Benchmark_CompareWithLiteral-4 21214032 52.18 ns/op Benchmark_CompareWithGlobalVar-4 36417091 31.03 ns/op

By using the -S compiler option, we could find that the compile generates less instructions for the function CompareWithGlobalVar than the function CompareWithLiteral. That is why the function CompareWithGlobalVar is more performant.

For small-size arrays, the performance difference between the two functions is small.

Please note that future compiler versions might be improved to remove the performance difference between the two functions.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.