3 ms·
> And because indexing by string is more harder task, including hash calculations if it's using hashtables as implementation FWIW, Lua uses string interning (h
by wahern 8y ago
> And because indexing by string is more harder task, including hash calculations if it's using hashtables as implementation
FWIW, Lua uses string interning (https://en.wikipedia.org/wiki/String_interning https://en.wikipedia.org/wiki/String_interning). The hash calculation for looking up _G["print"] occurred at compile time. _G["print"] should be as quick as indexing an array because the hash calculation is memoized and comparing string equality is equivalent to testing pointer equality. (Indeed, in a simple test both _G["print"] and _G[42] take about 1/10th of a second to iterate 4 million times on my circa 2012 Core i7.)
That said, using lexically bound locals (aka upvalues in Lua parlance) is indeed faster as loading the variable becomes a simple pointer dereference through the [anonymous] function object. A simple test suggests about 25% faster.
- tedunangst 8y ago_G[42] is probably still hitting the hash unless you populated it with 1 to 41.
- wahern 8y agoI was getting some spurious runs where the array access was slower, but didn't think it was worthwhile to mention in the post. Immediately after posting my curiosity got the better of me. After filling in _G[1,2048] the times were consistently the same. The code I was playing with: local n = 16777216 local _G = _G for i=1,2048 do _G[i] = i end do local start = os.clock() for i=1,n do local f = _G["print"] end print(os.clock() - start) end do local start = os.clock() for i=1,n do local f = _G[42] end print(os.clock() - start) end