51 points · by based2 · 7y ago · 8 comments
Wow, now this is deep!
Anyways, I liked the post. I also recommend:
http://lua-users.org/wiki/OptimisationTips
http://lua-users.org/wiki/OptimisationCodingTips
https://www.lua.org/gems/sample.pdf
Oh, and luajit! Mike Pall please come back!
It certainly doesn't help that GitHub renders tabs as 8 spaces wide instead of something more sane.
https://gist.github.com/realmonster/93090d4ef0b40c1b88d62f88...
FWIW, Lua uses 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.
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)
endI was struggling to hit 60fps so I devised this hacky system where I'd leave various markers in a "template" function, then parse that using Function.toString() and replace certain areas with unrolled loops, removed if conditions etc. Put the generated function code in a new Function() and used that for the remainder of the animation loop until settings changed.
Actually worked pretty well, along with some other optimizations, was able to hit 60fps in chrome and almost that in FF, depending on the scaling mode of course. At the time my manual implementation of bilinear filtering destroyed the frame rate no matter what, but these days browsers can run it without breaking a sweat. They've come a long way performance wise.
I still have it stashed away on my webserver, so here if anyone is curious. Code is a mess though: http://bigmooworld.com/pwings/pilotwings/pilotwings.html
You might recognize it..