Hi. First, this is not a question. Instead I’m posting the results of some (perhaps silly) questions that were floating around in the back of my mind.
(Get the code here if you want to test my results yourself.)
I’m a performance geek and sometimes I get these weird ideas about faster and slower ways of doing things. So, without further ado, let me expose my silly-ness.
Question #1 - for k,v in pairs() vs for _,v in pairs()
Is this:
-- Test 1 for \_,v in pairs( tbl ) do -- Uses '\_' to say, don't store value end
faster/slower than this:
-- Test 2 for k,v in pairs( tbl ) do end
(The key difference is the use of ‘_’ as a storage space instead of a variable. The real question here should be, “Is ‘_’ special to Lua or just another temporary variable name”)
After 10 runs x 1,000,000 iterations: No appreciable difference. ‘_’ must be just another variable and not special.
Question #2 - obj.fieldName vs obj[“fieldName”] lookups
Is this:
-- Test 1 for i = 1, iterations do if(obj.fieldName) then -- No work end end
faster/slower than this:
-- Test 2 for i = 1, iterations do if(obj["fieldName"]) then -- No work end end
(This question is about how Lua interprets the lookup request for a field named ‘fieldName’.)
After 10 runs x 1,000,000 iterations: No appreciable difference. I guess both bits of code generate the same or similar interpreted results.
Question #3 - Do we get a speedup for not re-creating temporary strings?
Is this:
-- Test 1 for i = 1, iterations do if(obj["fieldName"]) then -- No work end end
faster/slower than this:
-- Test 2 local index = "fieldName" for i = 1, iterations do if(obj[index]) then -- No work end end
(In this question, I’m trying to see how costly the creation of a temporary string is for doing lookups is. In test 1, I believe, a temporary string is created every iteration. Whereas, in test 2, the string is only created per run, right before the iteration code.)
After 10 runs x 1,000,000 iterations: Test #2 is slightly (2…3%) faster. This tells me that its not worth doing this unless it is part of a long chain of lookups or part of my code needs to have a programatically defined lookup value.
Question #4 - Same as #3 with subtle locality difference
Is this:
-- Test 1 local index = "fieldName" for i = 1, iterations do if(obj[index]) then -- No work end end
faster/slower than this:
-- Test 2 local index = "fieldName" function() for i = 1, iterations do if(obj[index]) then -- No work end end end
(This question is similar to #3, but in the second test of this case, the local variable containing the string is created outside the scope of a function that does the work. Will it be faster or slower?)
After 10 runs x 1,000,000 iterations: Whoa! Locality makes a big difference. Simply being outside the scope of the function has actually made case #2 20% slower than test #1. So, let that be a lesson. Locality is a crucial to speed.