Last Updated: May 29, 2023
·
28.55K
· afshinm

~~ is faster than Math.floor()

If you want to round a number downward in JavaScript, don't use Math.floor(), ~~ is faster.

Consider we have a pi variable that equals to 3.14 and we want to round it downward. So we can do:

var rounded = ~~pi; //result: 3

Instead of

var rounded = Math.floor(pi); //result: 3

Online benchmark: http://jsperf.com/math-round-vs

10 Responses
Add your response

True, but it clamps to 32 bit integer, so careful with big numbers ;)

over 1 year ago ·

Before you think about 'its faster' you should ask yourself if its worth. Take a look at the jsperf number on the slowest device Math.floor runs 3.5 millions ops/sec while ~~ runs 3.8 millions ops/sec. So sure it is faster but how often to you need a something that runs that often. The price for such mircro optimization is code that is hard to read for your coworkers.

over 1 year ago ·

I agree with @eskimoblood. There is no need to "optimize" this sort of thing. Like the old "single quote" vs "double quotes" on PHP. Your code just get worst. It just doesn't matter on production.

over 1 year ago ·
over 1 year ago ·

It may have it's downsides(32-bit int, etc.) but don't forget: if you use ~~ then that is 10 Characters less. If you use the function often enaugh that might help reduce bandwith. But then again only if you don't use HTTP compression(which you should).

Also some browsers actually handle ~~ slower. So when you say faster, this is not really true for all cases. Optimization should happen for all browsers.

over 1 year ago ·

Is there an equivalent shortcut for rounding up?

over 1 year ago ·

@stevenwadejr, you can use these sorts of things:

  • Math.floor: 0|n
  • Math.round: 0|n+.5
  • Math.ceil: 0|n+(n!=~~n))
over 1 year ago ·

Not in all browsers. I'm running Chrome 24 and Math.floor() is slightly faster, the jsperf aggregate results already reflect that.

It used to be the case some years back that this would benefit canvas animations and games, but these days we are in the hundreds of millions of operations/second, it's not worth hurting readability for it.

over 1 year ago ·

Two comments:

  • in some browsers, the test goes the other way: in Safari 5.1, Math.floor is faster.

  • the two are NOT EQUIVALENT for numbers < 0. Math.floor(-3.7) is -4, but ~~(-3.7) is -3.

over 1 year ago ·

Besides all the downsides of using ~~, I'll just leave this here about micro performance tests: http://www.youtube.com/watch?v=65-RbBwZQdU

over 1 year ago ·