I have multiple numbers (3 at least) each to test against a range obtained by a lower and an upper bound (I can be sure lower <= upper
condition is always satisfied).
Now having lower[1...n], x[1...n] and upper[1...n] my aims here are I'd like to optimize for performance...
I know, after I had a look at this other Q&A here on StackOverflow, I could go with an
(unsigned)(x[n]-lower[n]) <= (upper[n]-lower[n])
form
over the "classical" lower[n] <= x[n] && x[n] <= upper[n]
I need to go with JavaScript in this occasion, and I know I can obtain the same "trick" with this language using:
or by using JavaScript Uint32Array object
I'm quite sure the second method would have worst impact on performance so, excluding it on departure, and considering only the first one, I could do:
// Example 1
function everything_is_in_range(lower, x, upper) {
return ( ((x[0]-lower[0]) >>> 0) <= (upper[0]-lower[0]) &&
((x[1]-lower[1]) >>> 0) <= (upper[1]-lower[1]) &&
...
((x[n-1]-lower[n-1]) >>> 0) <= (upper[n-1]-lower[n-1]) );
}
Or I could do:
// Example 2
function everything_is_in_range(lower, x, upper) {
if ( ((x[0]-lower[0]) >>> 0) > (upper[0]-lower[0]) ) return false;
if ( ((x[1]-lower[1]) >>> 0) > (upper[1]-lower[1]) ) return false;
...
return ( ((x[n-1]-lower[n-1]) >>> 0) <= (upper[n-1]-lower[n-1]) );
}
My questions are:
will the unsigned shifting be not convenient on general performance so that I should stay with the "classical"
lower[n] <= x[n] && x[n] <= upper[n]
form for the purpose?in case the answer to my first answer is no, which way would be the most efficient one? But more important: do you know an even better one you could suggest maybe?
P.S. I know I could do with a for loop in the following way:
// Loop example
function everything_is_in_range(lower, x, upper) {
for (i=0; i<n; ++i) if ( ((x[i]-lower[i]) >>> 0) > (upper[i]-lower[i]) ) return false;
return true;
}
BUT
It would be only convenient for letting me write less code but it's something very analogue to the second code approach in the end, no?
I don't want to use this form because all values may happen to be passed as single separated parameters (that is my real case, in which I'm dealing with 3 or 4 numbers + bound ranges set of variables and I can't change this) and not as arrays of values (like in this example).