Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

doing something in an unusual but efficient way

I watched a video today and the guy in the video just write this to understand whether a number is even or not:

number/2*2 == number ? true : false ; 

i tried it when i got home and compared with

number % 2 == 0 ? true : false ; 

The second one was faster then i changed the first one as:

number>>1<<1 == number ? true : false; 

this time shifting the number once to the right and once to left worked faster :D The performance difference is not huge just 0-1 second for identifying all the numbers between 1 and 1000000000 but I liked it very much and wanted to hear such tricks from you.

so what else ? =)

and another idea from Russell Borogove =)

(number&1) == 0;

Results:

Time Elapsed With And Operation:00:00:07.0504033
Time Elapsed With Shift Operation:00:00:06.4653698
Time Elapsed With Mod Operation:00:00:06.8323908

Surprisingly shifting two times is working faster than a single and operation on my computer.

like image 283
mehmet6parmak Avatar asked Nov 05 '10 23:11

mehmet6parmak


1 Answers

MIT actually keeps a list of such things, HAKMEM, which can be found at http://www.inwap.com/pdp10/hbaker/hakmem/hakmem.html. Most of the programming-related ones are written in assembly language, but I understand that some of them have been translated to C at http://graphics.stanford.edu/~seander/bithacks.html.

Now for a lecture: These dirty tricks might be faster, but take far too long to comprehend.

Most computing isn't so performance-critical that tricks like this are necessary. In the odd-even case, number % 2 == 0 is much clearer and more readable than number/2*2 == number or number>>1<<1 == number. That said, in normal applications you should always use the simpler and more standard option because it will make your code easier to understand and maintain.

However, there are use cases for tricks like this. Especially in large-scale mathematical or scientific computing and computer graphics, tricks like these can save your life. An excellent example of this is John Carmack's "magic inverse square root" in Quake 3.

like image 89
Rafe Kettler Avatar answered Nov 15 '22 10:11

Rafe Kettler