Javascript Bitwise Operators or Math.Floor? Which is better?

by on Jul.15, 2011, under Software Development

I realized today that there are three ways to get at the floor of a value in Javascript.
There is:

  • the well-known Math.floor method
  • the lesser well-known Left-Shift <<operator (that I personally always use)
  • the even less well-known Double NOT ~~ operator
  • They all work similarly. Which is faster?

    I developed a test harness to compare the three different methods.

    The results? Math.floor is definitely the slowest.
    Safari processes the Left-shift << about 15% faster than the Double NOT ~~ operator
    Chrome effectively processes ~~ and << at the same speed
    Firefox processes Double NOT ~~ operator 6% faster than the Left-shift << operator
    IE8 processes Left-shift << operator 5% faster than the Double NOT ~~ operator

    Conclusion: use Left-shift << for a generalized, faster approach to getting at the floor of a value.

    Shannon Norrell

    1 Comment for this entry

    Leave a Reply

    Looking for something?

    Use the form below to search the site:

    Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!


    A few highly recommended websites...

    • A List Apart
    • Dive into HTML5
    • Javascript: The Good Parts
    • QuirksMode.org