4
votes

TEST 1: Localize

Code:

local min = math.min

Results:

Non-local: 0.719 (158%)
Localized: 0.453 (100%)

Conclusion:

Yes, we should localize all standard lua and Spring API functions.

Source: https://springrts.com/wiki/Lua_Performance

 

What is the reason for that performance boost?

1
Accessing local variable is just reading a value from some stack location. On the contrary, math.min means double looking into hash-part of table (searching math in globals table and searching min in table math) using CPU-intensive calculations of hash-function values of strings math and min. - Egor Skriptunoff
Try your timings also with just local math = math instead of local min = math.min. - lhf
This has nothing to do with functions, that is, the types of the values being accessed. It just relates to the complexity of the expression being evaluated to obtain the value. - Tom Blodget

1 Answers

7
votes

local min = math.min

Remember that table.name is just syntax sugar for table["name"] (they're exactly equivalent). And globals are just keys in the environment table, so math.min is _ENV["math"]["min"]. That's two hashtable lookups to get at the actual function value.

Copying the value into a local puts it in a VM register so there's no lookup.