I'm writing a game in Lua using Love2D.
Each entity obviously has an x,y position, which is just a table called "position" which holds {x, y} (i.e., {10, 4}).
Up until now I've been implementing the table using the array operator, so to get the x value, I'd invoke position[1], and to get y value I'd invoke position[2].
For readability, however, I'd much rather invoke position.x, and position.y. This would involve using the tables in their "map" style, like position = {x=10, y=4}.
While the array lookup time must obviously be O(1), I'm afraid using the map style would give worse results, due to the fact that maps tend to be a million times more complicated internally than a simple array.
In a way, I doubt the performance difference would matter much, even if it's called a million times a minute in my main game loop. I just want to have a better understanding of the tools I'm using to create this game.
Thanks!
Yes, array will always be faster than tables, however difference is usualy neglible compared to time spent on performing other tasks. Unless you will constantly access your new .x and .y keys in very tight loops with thousands of iterrations you shouldn't even bother.
However, if you do there's several apporoaches to mitigate any difference.
Localize your retrieved values:
-- Old - 3 lookups
result = obj.x + --[[ some long calculations ]] obj.x + --[[ more long calculations ]] obj.x
-- New - 1 lookup
local x = obj.x
result = x + --[[ some long calculations ]] x + --[[ more long calculations ]] x
Continue to use arrays, but define "constants" for index's magic numbers to improve readability
local X = 1
local Y = 2
print("Object coordinates are X: " .. obj[X] .. ", Y: " .. obj[Y])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With