Go: String & Conversion Optimization
ℹ️ This article is based on Go 1.14.
In Go, converting an array of bytes to a string could involve a memory allocation along with a copy of the converted string. However, converting bytes to a string just to satisfy a code constraint, such as a comparison in a switch statement or as a key in a map, is definitely a waste of CPU time. Let’s review some cases and the optimizations done.
Conversion
The conversion from an array of bytes to a string involves:
- An allocation for the new string on the heap if the variable outlives the current stack frame.
- A copy of the bytes to the string.
For more details about the escape analysis, I suggest reading my article “Go: Introduction to the Escape Analysis.”
Here is a simple program that goes through those two steps:
Here is a diagram of that conversion: