Speed of variables

Posted by tobiassjosten on Mon 20 Jun 2005 08:00 PM — 2 posts, 14,303 views.

Sweden #0
What's the difference in speed between these two examples?:
variable = false

.. and ..
if variable then variable = false end

I'm interested in numbers both when "variable" returns true and when it doesn't.
USA #1
variable = false is faster. Not by huge amounts, but it's faster.

I know that Lua doesn't translate directly into assembly, but here would be what MIPS assembly code would look like for both of those.

Assuming that 'variable' is in register $t0


variable = false
-->
move $t0, 0     # $t0 = false



if variable then variable = false end
-->
beq $t0, 0, DO_NOTHING     # if $t0 == 0, goto DO_NOTHING
move $t0, 0                # $t0 = false
DO_NOTHING:
...


The comparison instruction is generally speaking more costly than an assignment instruction. So, clearly, for a simple assignment of a boolean, variable=false is faster.

Explained differently, the comparison approach has to:
- load the current value
- compare it to something
- in some cases, store a new value

The direct assignment approach simply has to store a new value.

If you were really curious, you could run each version some 100,000 times and see which was faster. It is possible that Lua has some strangeness such that the first is faster on average but I doubt it.