Sunday, March 24, 2013

JavaScript: The less known parts. Bitwise Operators.

'JavaScript: The less known parts' chapters:
1. Bitwise Operators
2. Storage
3. Dom Mutations

Most of us probably use JavaScript every day - in my case it's building a mobile operating system in my daily job, preparing crazy and ridiculous demos for various conferences or run personal projects in my free time (mostly games). But even with years of experience (probably because the language itself is full of weird quirks and unintuitive patterns), from time to time I'm still getting surprised with new crazy hacks, techniques or workarounds. I want to put most of those things in one place and publish one every Monday - for last couple of years I wasn't really active on the blog, it's time to change this. First - bitwise hacking.


Bitwise operators

Most of us know know that there are some bitwise operators in JS. Every number has it's own binary representation, used by those operators. To check dec number's binary value, we use .toString() method with base argument - '2' for binary:


There are seven different bitwise operators. Assuming that variable a is equal to 5, and b is 13, those are actions and results of their operations:


Sometime we even use Bitwise OR as equivalent of Math.floor():


It has the same effect as double NOT operator (my favorite rounding solution since I first heard about it on Damian Wielgosik's workshop couple of years ago).


What about other real life examples of bit chaking? For instance, we can convert colors from RGA to Hex format:


We can also simply check which number in a pair is smaller (like Math.min) or bigger (Math.max):


Of course since Math library is really well optimized nowadays, using those hacks doesn't make any sense. But what about variables swap? Most common solution is to create a temporary variable to achieve that, what is not really efficient. It's simpler to use bit operations here:


Even with 'Pythonish' variable swap introduced in JavaScript 1.7, bitwise solution is the fastest way to achieve that.
JSPerf test [here]:


Great place to learn more bit-tricks to make your JS app: Sean Eron Anderson's site [Stanford PhD].
Do you know and use any more binary tricks in your JavaScript projects?

88 comments:

  1. Cool overview!

    I would like to point out that the delete operation in the 'temp variable' JSPerf case is what's slowing it down. The delete operation isn't valid anyway -- it won't succeed in function context and will return false.

    ReplyDelete
    Replies
    1. Can we see another JSPerf test without the delete line?

      Delete
    2. It's already there, in revisions of original test.

      Delete
  2. I still use a << 1 and a >> 1 as a shortcut for Math.floor( a * 2 ) and Math.floor( a / 2 );

    ReplyDelete
    Replies
    1. You can use 1 >> a as a shortcut for Math.pow(2, a)

      Delete
    2. i'm trying this in chrome devtools but it doesn't seem to work. the result is always 0.

      Delete
    3. for Math.pow(2,a) it has to be 1 << a

      Delete
  3. Temporary variable method seems to be faster on Chrome. And V8 doesn't recognize the JS 1.7 method.

    ReplyDelete
    Replies
    1. Of course, but anyway, temp var method in Chrome is almost twice slower than bitwise swapping in Firefox. And this method works only for integers, so I don't expect everyone to use it now, I just wanted to show that it's possible.

      Delete
    2. You can use !! for booleans (or perhaps Boolean()), although I'm not sure how quick it will be.

      Delete
  4. As Anonymous above said you should verify your final results with other browsers. Especially with Chrome.

    ReplyDelete
  5. Unless only gurus are expected to read the article, you should also mention that this works mostly for integer values (except the flooring with shifting or OR).

    ReplyDelete
  6. This article shows us interesting curiosities, which meant performance improvements some years ago. And I'm sure it still means performance improvements for JS being interpreted by powerful Internet Explorer JS engines.

    Concerning this binary variable exchange:
    We can extend the integer exchange without temporary variable to all numbers (representable with the available precision) with this commonly taught short operations:

    a += b;
    b = a-b;
    a -= b;

    and this is actually slower than previous binary operations, and even more slower than temporary variable usage.

    Concerning another use case for binary operations being faster than commonly used operator: checking if an integer i is a multiple of the integer b which is a power of 2.

    The test is:

    var amount = 1e4, i, b=32;

    console.time('%');

    i = amount;
    while(i--) { i%b }

    console.timeEnd('%');

    b-=1;

    console.time('&');

    i = amount;
    while(i--) { i&c }

    console.timeEnd('&');

    And the times I get on Chrome:
    %: 37.000ms
    &: 19.000ms

    However, setting the iteration amount to 1e5 is removing this time difference. And the reason is ?

    ReplyDelete
    Replies
    1. I meant "i&b" instead of "i&c".

      Delete
  7. var arr = [1,2,3];
    ~arr.indexOf(2); // => 1
    ~arr.indexOf(4); // => 0

    one's complement in base 10 turns -1 to 0 and all other numbers to not -1

    ReplyDelete
  8. Umm...I meant -1 to 0 and all other numbers to not 0

    Therefore
    ~x will coerce to false when x === -1
    ~x and to true otherwise

    ReplyDelete
  9. In the reg2hex function, I did not get the point for doing (1 << 24) and then doing substr(1). Why is it done?
    The above code is working without these two components too (atleast for the case of #BADA55 color)

    ReplyDelete
  10. Took me time to read all the comments, but I really enjoyed the article. It proved to be Very helpful to me and I am sure to all the commenters here! Its always nice when you can not only be informed, but also entertained! Im sure you had fun writing this article.
    Microsoft dynamics training

    ReplyDelete
  11. Fantastic article ! You havemade some very astute statements and I appreciate the the effort you have put into your writing. Its clear that you know what you are writing about. I am excited to read more of your sites content.

    Latest jobs

    ReplyDelete
  12. I can see that you are are genuinely passionate about this! great information.
    thank you...!
    Hadoop training

    ReplyDelete
  13. hi...Im student from Informatics engineering nice article,
    thanks for sharing :)

    ReplyDelete
  14. INTERNATIONAL CONCEPT OF WORK FROM HOME
    Work from home theory is fast gaining popularity because of the freedom and flexibility that comes with it. Since one is not bound by fixed working hours, they can schedule their work at the time when they feel most productive and convenient to them. Women & Men benefit a lot from this concept of work since they can balance their home and work perfectly. People mostly find that in this situation, their productivity is higher and stress levels lower. Those who like isolation and a tranquil work environment also tend to prefer this way of working. Today, with the kind of communication networks available, millions of people worldwide are considering this option.

    Women & Men who want to be independent but cannot afford to leave their responsibilities at home aside will benefit a lot from this concept of work. It makes it easier to maintain a healthy balance between home and work. The family doesn't get neglected and you can get your work done too. You can thus effectively juggle home responsibilities with your career. Working from home is definitely a viable option but it also needs a lot of hard work and discipline. You have to make a time schedule for yourself and stick to it. There will be a time frame of course for any job you take up and you have to fulfill that project within that time frame.

    There are many things that can be done working from home. A few of them is listed below that will give you a general idea about the benefits of this concept.

    Baby-sitting
    This is the most common and highly preferred job that Women & Men like doing. Since in today's competitive world both the parents have to work they need a secure place to leave behind their children who will take care of them and parents can also relax without being worried all the time. In this job you don't require any degree or qualifications. You only have to know how to take care of children. Parents are happy to pay handsome salary and you can also earn a lot without putting too much of an effort.

    Nursery
    For those who have a garden or an open space at your disposal and are also interested in gardening can go for this method of earning money. If given proper time and efforts nursery business can flourish very well and you will earn handsomely. But just as all jobs establishing it will be a bit difficult but the end results are outstanding.

    Freelance
    Freelance can be in different wings. Either you can be a freelance reporter or a freelance photographer. You can also do designing or be in the advertising field doing project on your own. Being independent and working independently will depend on your field of work and the availability of its worth in the market. If you like doing jewellery designing you can do that at home totally independently. You can also work on freelancing as a marketing executive working from home. Wanna know more, email us on workfromhome.otr214423@gmail.com and we will send you information on how you can actually work as a marketing freelancer.


    Internet related work
    This is a very vast field and here sky is the limit. All you need is a computer and Internet facility. Whatever field you are into work at home is perfect match in the software field. You can match your time according to your convenience and complete whatever projects you get. To learn more about how to work from home, contact us today on workfromhome.otr214423@gmail.comand our team will get you started on some excellent work from home projects.


    Diet food
    Since now a days Women & Men are more conscious of the food that they eat hence they prefer to have homemade low cal food and if you can start supplying low cal food to various offices then it will be a very good source of income and not too much of efforts. You can hire a few ladies who will help you out and this can be a good business.

    Thus think over this concept and go ahead.

    ReplyDelete
  15. This is very informative blog and i will share this blog.I have also created this blog for client side and server side scripting.Learn and create your first web app with angularjs.Here i have provided the very easy tutorial for this.

    Learn AngularJs from scratch

    ReplyDelete
  16. I time to time see some people using bitwise operators in the place of Math.floor(). I think this is totally unnecessary and better be avoided for the following reasons;
    1) Both are running almost at the same speed in all modern JS engines.
    2) They behave differently when the operant is a negative number. Such as ~~-2.14; // -2 however Math.floor(-2.14); // -3
    3) Making your code less readable and understandable won't make you any cooler coder.

    ReplyDelete
  17. Thank you so much for sharing this worthwhile to spent time on. You are running a really awesome blog. Keep up this good work Hadoop training institutes in chennai

    ReplyDelete
  18. Hello , I have been training students on AngularJS for past 6 months, and at times, I have used your blog as reference for the class training and also for my personal project development. It has been so much useful. Thank you, keep writing more:)
    AngularJS courses in Chennai

    ReplyDelete
  19. Thank you for the information , I wait for more information and I ask for a return visit our new website
    >> Obat pembesar penis <<

    ReplyDelete
  20. Hello , I have been training students on AngularJS for past 6 months, and at times, I have used your blog as reference for the class training and also for my personal project development. It has been so much useful. Thank you, keep writing more:)
    AngularJS training

    ReplyDelete
  21. There are lots of information about latest technology and how to get trained in them, like Best Hadoop Training In Chennai in Chennai have spread around the web, but this is a unique one according to me. The strategy you have updated here will make me to get trained in future technologies Hadoop Training in Chennai By the way you are running a great blog. Thanks for sharing this blogs..

    ReplyDelete
  22. I found some useful information in your blog, it was awesome to read, thanks for sharing this great content to my vision, keep sharing..
    SalesForce Training in Chennai

    ReplyDelete
  23. Pretty article! I found some useful information in your blog, it was awesome to read,thanks for sharing this great content to my vision, keep sharing..
    Unix Training In Chennai

    ReplyDelete
  24. This information is impressive..I am inspired with your post writing style & how continuously you describe this topic. After reading your post,thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic..
    Android Training In Chennai In Chennai

    ReplyDelete
  25. SAP Training in Chennai
    This post is really nice and informative. The explanation given is really comprehensive and informative..

    ReplyDelete
  26. Oracle Training in chennai
    Thanks for sharing such a great information..Its really nice and informative..

    ReplyDelete
  27. Selenium Training in Chennai
    Wonderful blog.. Thanks for sharing informative blog.. its very useful to me..

    ReplyDelete
  28. Data warehousing Training in Chennai
    I am reading your post from the beginning, it was so interesting to read & I feel thanks to you for posting such a good blog, keep updates regularly..

    ReplyDelete
  29. Whatever we gathered information from the blogs, we should implement that in practically then only we can understand that exact thing clearly, but it’s no need to do it, because you have explained the concepts very well. It was crystal clear, keep sharing..
    Websphere Training in Chennai

    ReplyDelete
  30. Oracle DBA Training in Chennai
    Thanks for sharing this informative blog. I did Oracle DBA Certification in Greens Technology at Adyar. This is really useful for me to make a bright career..

    ReplyDelete
  31. This is really an awesome article. Thank you for sharing this.It is worth reading for everyone. Visit us:
    Oracle Training in Chennai

    ReplyDelete
  32. very nice blogs!!! i have to learning for lot of information for this sites...Sharing for wonderful information.Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing.
    Oracle DBA Training in Chennai

    ReplyDelete
  33. great article!!!!!This is very importent information for us.I like all content and information.I have read it.You know more about this please visit again.
    Oracle RAC Training in Chennai

    ReplyDelete
  34. Wonderful tips, very helpful well explained. Your post is definitely incredible. I will refer this to my friend.
    SalesForce Training in Chennai

    ReplyDelete
  35. I am reading your post from the beginning, it was so interesting to read & I feel thanks to you for posting such a good blog, keep updates regularly.
    Java Training in Chennai

    ReplyDelete
  36. Really awesome blog. Your blog is really useful for me. Thanks for sharing this informative blog. Keep update your blog.
    PHP Training in Chennai

    ReplyDelete
  37. Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing.Nice article i was really impressed by seeing this article, it was very interesting and it is very useful for me..
    Android Training in Chennai

    ReplyDelete
  38. Really awesome blog. Your blog is really useful for me. Thanks for sharing this informative blog. Keep update your blog.
    SAP Training in Chennai

    ReplyDelete
  39. Excellent information with unique content and it is very useful to know about the information based on blogs.
    Hadoop Training in Chennai

    ReplyDelete
  40. Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing.
    Regards,
    Informatica training in chennai|Informatica courses in Chennai

    ReplyDelete
  41. WHAT is WITH these SPAM COMMENTS PROMOTING CRAP?
    Seriously am I the only one here who actually wants to learn Javascript?

    Also these spam comments are weird. The following is my interpretation of them.
    "AwawwwW ur Atcisle wes suhh niccceeee nowww CLICK MY ******* LINK TO GET A VIRUS SO I CAN HAX UR COMPUTAHHHH"

    Btw I don't get how ~5 = -6

    ReplyDelete
  42. WHAT is WITH these SPAM COMMENTS PROMOTING CRAP?
    Seriously am I the only one here who actually wants to learn Javascript?

    Also these spam comments are weird. The following is my interpretation of them.
    "AwawwwW ur Atcisle wes suhh niccceeee nowww CLICK MY ******* LINK TO GET A VIRUS SO I CAN HAX UR COMPUTAHHHH"

    Btw I don't get how ~5 = -6

    ReplyDelete
  43. Learning new technology would give oneself a true confidence in the current emerging Information Technology domain. With the knowledge of big data the most magnificent cloud computing technology one can go the peek of data processing. As there is a drastic improvement in this field everyone are showing much interest in pursuing this technology. Your content tells the same about evolving technology. Thanks for sharing this.

    Hadoop Training in Chennai | Hadoop Training Chennai | Big Data Training in Chennai | Big Data Training Chennai

    ReplyDelete
  44. Thank you for this detailed article on web designing course in Chennai. It has been really helpful during my web designing training in Chennai, as I used the details in your web designing courses in Chennai as a reference to my students.

    ReplyDelete
  45. Excellent Post, I welcome your interest about to post blogs. It will help many of them to update their skills in their interesting field.
    Regards,
    sas training in Chennai|sas course in Chennai|sas training institute in Chennai

    ReplyDelete
  46. I have finally found a Worth able content to read. The way you have presented information here is quite impressive. I have bookmarked this page for future use. Thanks for sharing content like this once again. Keep sharing content like this.

    Software testing training in chennai | Testing courses in chennai | Manual testing training in Chennai

    ReplyDelete
  47. There is a huge demand for professional big data analysts who are able to use the software which is used to process the big data in order to get accurate results. MNC's are looking for professionals who can process their data so that they can get into a accurate business decision which would eventually help them to earn more profits, they can serve their customers better, and their risk is lowered.
    big data training in chennai|big data training|big data course in chennai|big data training chennai|big data hadoop training in chennai

    ReplyDelete
  48. Nice article. The return statement "return '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).substr(1);" could be even cleaner with an or statement instead of those additions, like "return '#' + ((1 << 24) | (r << 16) | (g << 8) | b).toString(16).substr(1);"

    ReplyDelete
  49. Nice article. The return statement "return '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).substr(1);" could be even cleaner with an or statement instead of those additions, like "return '#' + ((1 << 24) | (r << 16) | (g << 8) | b).toString(16).substr(1);"

    ReplyDelete
  50. I found this very helpful,..
    Thanks for the share,..
    angularjs course

    ReplyDelete
  51. Really awesome blog. Your blog is really useful for me. Thanks for sharing this informative blog. Keep update your blog.
    Oracle Training In Chennai

    ReplyDelete
  52. Best SAS Training Institute In Chennai It’s too informative blog and I am getting conglomerations of info’s about Oracle interview questions and answer .Thanks for sharing, I would like to see your updates regularly so keep blogging.

    ReplyDelete
  53. Really awesome blog. Your blog is really useful for me.
    Thanks for sharing this informative blog. Keep update your blog.
    Oracle Training In Chennai

    ReplyDelete
  54. Best Java Training Institute In ChennaiThis information is impressive; I am inspired with your post writing style & how continuously you describe this topic. After reading your post, thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic..

    ReplyDelete
  55. What does this mean:
    "it's equivalent of 14.0.toString where we can
    // show that decimal part of the number is equal to 0."

    What is the decimal part?

    ReplyDelete
  56. Great post....Thank you for posting the great content……I found it quiet interesting, hopefully you will keep posting such blogs…
    If you Want more seo course in chennai

    ReplyDelete