Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Is it faster to declare a variable inside or outside of a loop?

Asked by 8 years ago

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):

local x;
for i = 1, 10000 do
    x = SomeFunction(i);
    print(x);
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?

for i = 1, 10000 do
    local x = SomeFunction(i);
    print(x);
end
0
Benchmark it yourself... `start = tick()` before the loop, and then `print(tick() - start)` after. XAXA 1569 — 8y
0
I did once, and the first was faster, but someone in the forums said that it was faster to localize it inside the loop. I just tried it again with SomeFunction being recursive, and outside of the loop is much faster. Thanks for the suggestion. nicemike40 486 — 8y

2 answers

Log in to vote
0
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
8 years ago

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.

0
I know it doesn't matter a ton usually, but I've been in situations in the past where minor improvements like this had to be taken into account. Thanks for the response - no need to look into it further. nicemike40 486 — 8y
Ad
Log in to vote
-1
Answered by 8 years ago

I just did the benchmark myself, and it turns out the first was much faster.

The code I used:

local start;
local function Modify(n)
    if (n == 0) then return 0 end;
    return 1+Modify(n-1);
end

start = tick()
local x;
for i = 1, 10000 do
    x = Modify(i);
end
warn(("%dms outside of loop"):format(tick()-start));


start = tick()
for i = 1, 10000 do
    local x = Modify(i);
end
warn(("%.1fms inside of loop"):format(1000*(tick()-start)));

--> 12ms outside of loop
--> 12054.4ms inside of loop
0
12 and 12 are the same. You have a 1000* in the second. There is no significant difference. BlueTaslem 18071 — 8y
0
Well. That was silly. It's late and I'm sick? Thanks nicemike40 486 — 8y

Answer this question