I have noticed while developing on my addon that sometimes, when messing with functions which are continuously called from "OnUpdate" frame scripts, the memory usage for my addon start to rise aggressively (like +2kb per sec). I am quiet sure that local variables in the called functions are the guilty ones for this rise in memory usage.
--this stuff is continuously updated
I guess new memory for those local variables are allocated all the time, and then the garbage collector kicks in once in a while to clean up and then the rise of memory usage starts over again.
If my assumption is correct, is it then better to refrain from using local variables in such functions and use global ones instead? OR is it best to use local variables because they use less CPU to access compared to global variables?
Access to global variables in for example C programming is CPU expensive, but then again C is stack-based and Lua is register-based-VM...
Memory growth of that sort would be due to local variables only if those local variables are new tables; OnUpdate() is fired every screen refresh, so at 60FPS you'd be creating 60 new tables per second.
ok thank you didn't think about that as I just tend to put all my functions and stuff into tables and use local variables inside my functions all the time.
Guess I have some optimization to be gained then :)
To make it clear : using local vars is usually fine. They are created on the stack and freed once the function ends. Using existing tables is usually fine. What is bad is creating new tables inside your functions, whether you put these table in local variables or elsewhere.
Strings are allocated in the heap and freed by the garbage collector. However, if the computation returns a string that is already in use, it returns the existing string instance instead of creating a new one. However this is totally transparent for the programmer, and unless your function creates a lot of unique strings, you should not care about it.
Moreover, explicitly cleaning up local variables has no effect, as leaving their scope has the same effect.