description
I am trying to find out the best practice for writing a loop which does one check and at the same time has to increment a value so that the whilewhile
loop will eventually fail. Performance is important that's why I thought of using the least amount of variables.
use case
Use case
In a decently low level method I do a binarySearch(array, key)
which guarantees to find a key
value in a sorted array
if the key can be found. However it does not guarantees to find the first or last key first. But since I need the range of indexes in which the key excists (for other code later on) I try to find the last and first element in the array that matches. With this code I am trying to let lastSucceedingIndex
hold the last index
which holds the key
:
while (lastSucceedingIndex < tailIndex && (array[++lastSucceedingIndex] == key)) {
}
lastSucceedingIndex--;
There is one situation in which a bug exists, namely when the lastSucceedingIndex
is equal to the tailIndex
: the while loop will fail and the ++lastSucceedingIndex
will not happen. The lastSucceedingIndex--
is there in the end to fix the ++lastSucceedingIndex
when it's not equal to the key
, but since this does not happen in the last case it will decrement lastSucceedingIndex
incorrectly. I wrote this loop for performance and I take this little bug for granted, it happens so rarely that it will effect less than 0.001% of all cases. This way it seems like I only need one counter and one variable, the loop could be executed as much as 17000 times before it finds its lastSucceedingIndex
and the array is very large with possibly up to a million entries.
Alternatives for performance and readability?
Are there any alternatives for performance and readability?
I analysedanalysed my code by the build in code analysis of my IDE and I get the remark
while statement has empty body at line
Which seems to indicate that having a loop with no lines in them is considered a possible bug by the compiler or at least bad practice.
Now Now my question is, is having an empty loop considered bad practice? I could move the lastSucceedingIndex
to the body and make it bug-free but that would require one extra addition like so:
while (lastSucceedingIndex < tailIndex && array[lastSucceedingIndex + 1] == key) {
lastSucceedingIndex++;
}
1 less bug for millions upon millions of extra assembly instructions seems a hard trade-off to make.