Usually when I have a variable that I'm going to reuse, I do something like this to reuse memory (I'm not even sure Lua does that):
1 | local x; |
2 | for i = 1 , 10000 do |
3 | x = SomeFunction(i); |
4 | print (x); |
5 | end |
Would it be faster (I know its basically negligible, but still) to declare it inside of the loop so that the compiler doesn't have to leave the scope at all?
1 | for i = 1 , 10000 do |
2 | local x = SomeFunction(i); |
3 | print (x); |
4 | end |
In my micro-benchmarks in Lua 5.1 in the command line (which isn't going to be exactly the same as ROBLOX) I get that inside the loop is about 5% faster.
However, these sorts of things shouldn't really make a difference. This is called microoptimizations and worrying about them wastes your time.
The things that make your code fast are algorithmic improvements, not making getting or setting a variable 4% faster. That is not where you are spending your time. You are spending your time traversing lists and computing large objects.
Defining variables in the narrowest scope possible is good practice, so that's what you should do. You shouldn't really expect a difference in performance because they're all stack allocated anyway. I can do some digging as to why one might be faster than the other, but you really shouldn't have to worry about the answer.
I just did the benchmark myself, and it turns out the first was much faster.
The code I used:
01 | local start; |
02 | local function Modify(n) |
03 | if (n = = 0 ) then return 0 end ; |
04 | return 1 +Modify(n- 1 ); |
05 | end |
06 |
07 | start = tick() |
08 | local x; |
09 | for i = 1 , 10000 do |
10 | x = Modify(i); |
11 | end |
12 | warn(( "%dms outside of loop" ):format(tick()-start)); |
13 |
14 |
15 | start = tick() |