I figured that everyone here must have experimented with different approaches to coding their algorithms to check out which methods yielded the fastest calculation times or used the least memory. Why not compile all these findings in a single thread where everyone can benefit from it?
I’ll start with some of my findings. If these come across as basic knowledge to you, just add on your more advanced methods and we can all learn.
- Using numbered indices in a Lua table is faster than using a hash table when you have to loop through the entire table.
Essentially,
[lua]for i=1,#array do[/lua]
is faster than
[lua]for k,v in pairs(array) do[/lua]
or ipairs for that reason.
Hash tables are useful for easily storing objects by their reference addresses though, which could potentially save some cycles in cases where you don’t have to loop through everything. However the catch is you cannot obtain the size of the hash table using #array. You’d have to loop through the entire table to sum it all up.
-
If you’re using numbered tables/arrays,
[lua]array[#array+1] = newItem[/lua]
is faster than
[lua]table.insert(array,newItem)[/lua] -
When carrying out exponential calculations, I found that
[lua]value = value^power[/lua]
is faster than
[lua]math.pow(value,power)[/lua]
For powers of 2,
[lua]value=value*value[/lua]
is the fastest. However, for any powers above the power of 2, usage of the binary operator ‘^’ would yield the fastest results.
I’ll post up more stuff when I find them. Note that these time improvements are very minute, and I did the experiments by looping the calculations for a million times for the time discrepancy to appear. But hey, won’t harm to improve timings by 0.000001 ms eh. [import]uid: 108204 topic_id: 27875 reply_id: 327875[/import]