Better Performance in LUA: var.state or var["state"]?

I have a variable the stores the state of the player. In order to prevent excessive string compares every frame cycle (i.e. myState == “flying”), I’ve stored everything in an array (i.e. var.flying = 1, var.ground = 2, etc).

I would like to take it a step further and ask, which is more efficient?

var.flying

or

var[“flying”]

Or does it even make a difference? The second is easier if I want to use a variable for reference (var[state]), but I’m wondering impacts performance and by how much. Thanks!

Hi @harb37,

I won’t say with 100% authority, but I seem to recall reading once that the second way is slightly more efficient… but I can’t imagine it would make any significant impact unless you’re doing this in some crazy loop of 500,000 iterations or something. :slight_smile:

Brent

makes no difference, they’ll both compile to exactly the same vm code (just a SETTABLE if local, or a GETTABUP+SETTABLE if global; assuming an assignment, similar for a retrieval). this is known as “syntactic sugar” - just two different ways of writing the same thing.

Thanks Brent and Dave! It probably won’t have much of an impact on my current project. I was more curious than anything. I’m a optimization freak :slight_smile:

Hi @harb37,

I won’t say with 100% authority, but I seem to recall reading once that the second way is slightly more efficient… but I can’t imagine it would make any significant impact unless you’re doing this in some crazy loop of 500,000 iterations or something. :slight_smile:

Brent

makes no difference, they’ll both compile to exactly the same vm code (just a SETTABLE if local, or a GETTABUP+SETTABLE if global; assuming an assignment, similar for a retrieval). this is known as “syntactic sugar” - just two different ways of writing the same thing.

Thanks Brent and Dave! It probably won’t have much of an impact on my current project. I was more curious than anything. I’m a optimization freak :slight_smile: