|
how many times you've got calculations like this:
z=Math.round((x+y)/2);
usually I use it to calculate new position for objects that shuold be on integer _x or _y, like texts or small images (to avoid blur).
so, what computer do in this case?
first operation: x+y second operation: first_result / 2 third operation: Math.round( second_result ) fourth operation: z = third_result
and thats it.
can we do it faster ?
yes.
how?
bitwise shifting!
z=x+y>>>1;
in this case operations are: first operation: x+y second operation: first_result>>>1 third operation: z = second_result
one step less, 25% faster.
bitwise shifting directly change individual bits in an operand, so it is so fast that it could not be faster. also, what is important, allways returns integer, so - it is not neccessary to round() it.
in this case it is like this:
first_result >>>1 means DIVIDE first_result WITH 2¹
first_result >>>2 would means DIVIDE first_result WITH 2²
first_result >>>n would means DIVIDE first_result WITH 2n
etc
IMPORTANT: works only with positive numbers.
|