Golang Tips
Go is a high-performance language, but that does not mean we can ignore performance. Here are some tips related to programming and performance.
- If you need to convert numbers to strings,
strconv.Itoa()is about twice as fast asfmt.Sprintf(). - Avoid converting
Stringto[]Bytewhere possible. This conversion hurts performance. - If you use
append()on a slice inside a for-loop, expand the slice capacity ahead of time to avoid reallocations and automatic growth by powers of two, which can waste memory. - Use
StringBufferorStringBuildto concatenate strings; they are three to four orders of magnitude faster than+or+=. - Use concurrent goroutines where possible, and use
sync.WaitGroupto synchronize concurrent work. - Avoid allocating in hot paths; it makes the GC busy. Use
sync.Poolto reuse objects. - Use lock-free operations and avoid mutexes when possible; use
sync/Atomic. (See Lock-Free Queue Implementation or Lock-Free Hashmap Implementation.) - Use I/O buffering; I/O is very slow.
bufio.NewWrite()andbufio.NewReader()improve performance. - For fixed regex patterns in a for-loop, use
regexp.Compile()to precompile; it improves performance by two orders of magnitude. - If you need higher-performance protocols, consider protobuf or msgp instead of JSON, because JSON serialization/deserialization uses reflection.
- When using maps, integer keys are faster than string keys because integer comparisons are faster.
