When do I need to worry about memory?
The short answer is: only when you have to worry. Generally Lua does The Right Thing, but if memory use is excessive, then you do need to understand something about memory management in Lua.
People can get anxious about having a lot of string objects in memory. But Lua interns strings, so that there is really only one copy of each distinct string. So this code uses less memory than you would think:
local t = {}
for i = 1,10000 do
t[i] = {firstname = names[i], address = addr[i]}
end
It also makes string equality tests very fast.
Excessive string concatenation can be slow and inefficient. Here is the wrong way to read a file into a string:
local t = ""
for line in io.lines() do
t = t .. line .. '\n'
end
This is bad, for the same reason that doing this in Java or Python would be a bad idea; strings are immutable, so you are constantly creating and discarding strings.
If you do need to concatenate a lot strings, put them into a table and then stitch them together with table.concat()
Lua, like most modern languages, is garbage-collected. Memory allocated for tables, etc is automatically collected when the data is no longer referenced. Say we have t = {1,2,3}
and later the assignment t = {10,20,30}
happens; the original table is effectively orphaned, and gets collected next time the garbage collector comes around.
So the first thing to bear in mind is that data memory will only be freed if you genuinely have no references to that data. And the second is that it will generally not happen at the time of your choosing, but you can force a collection with collectgarbage('collect')
. A subtle point here is that calling this function twice is often needed, because any finalizers will be scheduled for execution in the first pass, but will only execute in the second pass.