animals = {}
animals["lion"] = {species = "lion", speed = "50", feet = {}}
-- This is not as easy to understand
animals["lion"].feet.topright = {}
-- This is simpler than before
local lion = animals["lion"]
local lionFeet = lion.feet
lionFeet.topright = {}
Basically: It's simpler, and, if you have a really big program, you can save some bytes too.
It makes no sense to repeat a long dereference chain again and again. The repeated dereferencing is just noise which distracts from the signal (the logic of the algorithm).
According to the documentation there is no performance gain if you use LuaJIT and if you have performance issues the first step should be to switch to LuaJIT, not to fool around with your code i.e. you shouldn't do it for performance reasons.
The local variables are speedy because they're kept in "registers" and the Lua internal compiler does things to connect those variable names to the registers. Like, you write local field and the compiler names the first register "field" and knows to use the first register every time it finds field. So, Yes! Use the registers, and use them a lot. However! There's only about 200 of them for a lexical scope, and each scope inherits its parent's registers. I don't think anyone ever hits that limit in practical code, but bear in mind that you can't make the entire world local.
So this is mostly about code simplicity but there are also performance reasons! I didn't know that, thanks Hexenhammer and Inny for tips about Lua interpreter internals and LuaJIT!
Note that the performance advantage is usually neglible. I've been programming for nine years now, and I've never come across a situation where something like this actually made a difference performance wise.
If your game is ever too slow, it won't be because you use animals["lion"].feet instead of lion.feet. It will be because one or more of the following:
One of your algoritms is not smart enough.
One of your algorithms is trying to solve a problem that is too difficult.
You have too much data that needs to be processed.
Robin wrote:It will be because one or more of the following:
One of your algoritms is not smart enough.
One of your algorithms is trying to solve a problem that is too difficult.
You have too much data that needs to be processed.
Your hardware is simply not fast enough.
You're repeating something slow every frame instead of saving the results (often seen as love.graphics.newFont in love.draw...).
Earliest Love2D supporter who can't Love anymore. Let me disable pixel shaders if I don't use them, dammit! Lenovo Thinkpad X60 Tablet, built like a tank. But not fancy enough for Love2D 0.10.0+.
Inny wrote:Since we're getting into performance tips, I'm going to make a quote out of Lua Gems, Chapter 2: Lua Performance Tips, by Roberto Ierusalimschy.
Rule #1: Don't do it.
Rule #2: Don't do it yet. (for experts only)
I think that's actually a quote from Michael A. Jackson.