Would it be more efficient to search for something trough a small table loop (the table has 1 to 3 entries) or by checking a 2nd table with an if
statement (this table is much bigger and can have hundreds of entries).
Loop though table:
for (var i = 0; i < TableA.length; i++) {
if (TableA[i].x1 < x && TableA[i].x2 < x && TableA[i].y1 < y && TableA[i].y2 < y then) {
// process ..
break;
}
}
if statement:
if (tableB[x][y] == true) {
// process ..
}
My guess is that the option with the if
statement is faster with the drawback of the memory needed for the bigger table.
Speaking of practical performance it's often an hard game and you should profile your code to check if there is an huge penalty in one of the two proposed approach.
The if statement is an O(1) while the loop table is an O(n), but as you already said the n is really small (1 to 3), so it's hard to say which version is the faster one.
It depends a lot on the size of the tableB: if the table is very huge, it may not fit on the CPU-cache, so the access may involve a read through the RAM (or slower CPU-cache) and while the code is still O(1), the memory-access dominates the compute-time. On the other hand, the tableA is small and the arithmetic operations involved on the if statement are easy enough that can be neglectable for the CPU performance (depending on the architecture of the CPU).
So, my advise is to profile your code with a real dataset to understand if there is a difference of performance worthing for the optimization. If the difference is small enough, I agree with the user helvete and I would choose the loop way to be more future-proof.
Many years ago I used to spent lot of time to optimize code not worthing of it, resulting in a dirty code-base more difficult to maintain. Now I often recall myself the following citation:
premature optimization is the root of all evil
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