Things you should know about Lua's performance

This wiki is a result of some lua performance tests (the widget is included with ca sandbox).


TEST 1: localize

normal way: 0.719 (158%)
localized: 0.453 (100%)
  -> Yeah, we should localize all used funtions.

TEST 2: localized class-methods (with only 3 accesses!)

normal way: 1.203 (102%)
localized: 1.172 (100%)
  -> No, it isn't faster to localize a class method IN the function call.

TEST 3: unpack a table

with [ ]: 0.485 (100%)
unpack(): 1.093 (225%)
custom unpack4: 0.641 (131%)
  -> Don't use unpack() in time critical code!

TEST 4: determine maximum and set it ('>' vs. max)

math.max: 0.437 (156%)
'if > then': 0.282 (100%)
  -> Don't use math.[max|min]() in time critical code!

TEST 5: nil checks ('if' vs. 'or')

nil-check: 0.297 (106%)
a=x or y: 0.281 (100%)
  -> WOW! the or-operator is faster than a nil-check. Use it! :D

TEST 6: 'x2' vs. 'x*x'

x^2: 1.422 (110%)
x*x: 1.297 (100%)

TEST 7: modulus operators (math.mod vs. %)

math.mod: 0.281 (355%)
%: 0.079 (100%)
  -> Don't use math.mod()!

TEST 8: functions as param for other functions

defined in function param: 3.890 (1144%)
defined as local: 0.344 (100%)
  -> REALLY, LOCALIZE YOUR FUNCTIONS ALWAYS BEFORE SENDING THEM INTO ANOTHER FUNCTION!!!
     i.e if you use gl.BeginEnd(), gl.CreateList(), ...!!!

TEST 9: for-loops

pairs (key+value): 3.078 (217%)
pairs (value only): 3.062 (216%)
ipairs: 3.344 (236%)
for i=1,x do: 1.422 (100%)
for i=1,#atable do 1.422 (100%)
for i=1,atable_length do: 1.562 (110%)
  -> Don't use pairs() or ipairs()!
     Try to save the table-size somewhere and use "for i=1,x do"!

TEST 10: array access (with [ ]) vs. object access (with .method)

atable["foo"]: 1.125 (100%)
atable.foo: 1.141 (101%)

TEST 11: buffered table item access

'a[n].x=a[n].x+1': 1.453 (127%)
'local y=a[n]; y.x=y.x+1': 1.140 (100%)

TEST 12: adding table items (table.insert vs. [ ])

table.insert: 1.250 (727%)
a[i]: 0.172 (100%)
a[#a+1]=x: 0.453 (263%)
a[count++]=x: 0.203 (118%)
  -> Don't use table.insert!!!
     Try to save the table-size somewhere and use "a[count+1]=x"!