[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: Temporary local variables
- From: JP Florijn <jpflorijn@...>
- Date: Wed, 2 Jan 2013 14:12:44 +0100
This'll work more or less the same as it does in C, except for the role of the GC and dynamic typing.
Every distinct variable you allocate needs to be de-allocated by the garbage collector once it goes out of scope. So if you declare a dozen variables, that is a dozen objects the GC needs to mark and collect. If you declare two variables and re-use them with objects of the same type, thats only two variables to mark and collect.
Will there be any performance gain? Yes; fewer allocations and fewer GC collections, if the objects get collected at all (at the default Lua pause of 200, the GC often won start a cycle once the program drops into a state where memory usage stabilizes).
Note, however, that dynamic typing clouds the issue. If you were to define 'a' first as a number, then later as a string, the variable could not be reused, and the only difference is that the GC might be able to collect the first number at some earlier time - though it is unlikely that it will, the GC working as it does.
On Wed, Jan 2, 2013 at 4:59 AM, Marc Lepage <firstname.lastname@example.org>
Say I have an object with about a dozen properties A-L.
I want to process them in small groups, something like:
local a, b = o.a, o.b
if a or b then
local c, d = o.c, o.d
It happens that I don't need to use AB after I go on to CD. Yet, I get them into separate local variables.
I am just wondering, will it be any kind of performance gain if I were to reuse the same local variables for CD as for AB?
I mean, what would be going on under the hood, and could a gain be reasonably expected (assuming these functions are called often on lots of objects)? Would it reduce the amount of memory churn?
I think it's more readable as it is, but if it were good practice to reduce the amount of locals in this function (say from 12 to 2) for a gain I'd be willing to do that. Mostly I'm just curious what the difference would be.