4

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?

816-8055
  • 509
  • 7
  • 15
  • 6
    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 Oct 05 '15 at 09:42
  • 1
    Try your timings also with just `local math = math` instead of `local min = math.min`. – lhf Oct 05 '15 at 10:51
  • 5
    Possible duplicate of [Is there any performance value in creating local copies of Lua functions?](http://stackoverflow.com/questions/18093728/is-there-any-performance-value-in-creating-local-copies-of-lua-functions) – Yu Hao Oct 05 '15 at 10:53
  • 1
    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 Oct 05 '15 at 22:20

1 Answers1

7

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.

Mud
  • 28,277
  • 11
  • 59
  • 92