Originally Posted by jeruku
Though, garbage collection is slightly more forgiving for strings... if only a little.
|
Strings in general are strange in Lua. They're stored by a hash of their content. So two strings of equal content always point to the same object in memory.
Concatenation, while it seems innocuous, is actually the biggest issue with memory bloat when it comes to strings. With each concatenation operation, you add a copy of said string with whatever piece you appended to it.
Example:
Code:
print("some".." ".."sample".." ".."text")
To break this down, each segment is its own string, so we start out with 4 (remember, the spaces are the same string object since they are equal). Each concatenation step adds a new string to memory containing the result of the operation. After this is done, we have 4 more strings in memory. This means this one line created 8 strings, the last of which is the completed expression that gets printed out.
Another big issue with strings is formatting them with numbers. Each time you format a string with numbers, each unique combination of numbers produces a new string object.