Is multiple assignment less efficient?

Consider the following:

unrelated1, unrelated2 = 1, "Hello"

Will that actually be less efficient than this:

unrelated1 = 1
unrelated2 = "Hello"

I heard a mention of multiple assignment entailing ‘temporary registers’ but is the same true for single assignment?

I did a quick benchmark and it appears multiple assignment is very marginally faster, especially when assigning to multiple global variables or something. Any idea why that might be? I was expecting it to be identically fast or even slightly slower.

Mini disclaimer: I haven’t had the time to properly dive into how the parser handles assignments.

Short answer: standalone assignment is a bit faster than parallel assignment - a couple of times, the latter gets slower with more assignments.

Mind sharing your benchmark? I’m positive there must have been a hidden factor involved.

As far as I know you’re right and both vanilla Lua and Luau have these temporary registers where results from evaluation of the right hand side are stored before the values are assigned. Furthermore, I remember zeuxcg mentioning that multiple assignments are more optimised when no destruction is taking place (like table unpacking).

Should this knowledge affect the way you code?

Certainly not! The difference is so negligible in the grand scheme of things that the decision about using it, except in extreme cases, is based solely on your readability preferences.

local x = tick(); for i = 1, 10000000, 1 do a, b = 1, 2 end; print(tick()-x)

That takes about 0.12 seconds.

local x = tick(); for i = 1, 10000000, 1 do a = 1; b = 2 end; print(tick()-x)

That takes about 0.16 seconds.

Sorry for the late reply. Looks like some other optimisation was applied in my benchmark.

The result is quite surprising to me, maybe it has something to do with:

There should still be some copying from temp registries happening under the hood on the cpp side though.

Edit. @asadefa also found this:

image
(Performance - Luau)

Also, out of curiosity, are you going off my numbers, or did you run also run my benchmark yourself? Were you able to replicate my results?

I could repo the difference, except I also switched to os.clock() and tried with even more vars in which case the difference was less noticeable. Also, I later localised them.

Re the edit: So basically, what that means to me, is some times performing the assignments in a certain order could be more efficient, e.g., for cache efficiency reasons or something. Multiple assignment basically leaves the order unspecified and able to be optimized, but doing them one at a time forces them to be performed in a specific, possibly sub-optimal order.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.