9b6ksa
Last Updated: February 25, 2016
·
9.748K
· afshinm
Add92525ab635b5119671269d24c1449

~~ 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

Say Thanks
Respond

10 Responses
Add your response

2432
781bbe3e6880c14f783d044f2ff05e50

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

over 1 year ago ·
2434
7831f9c652845c34091da263b689cc25

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 ·
2435
Profile 2015 2

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 ·
2442
995874 10203292335448877 1165866291 n
over 1 year ago ·
2446
Bae16dbfb2dcfb36d3d9bb9bce7bf3db

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 ·
2497
8b8731cc8fc06877833590f617792af8

Is there an equivalent shortcut for rounding up?

over 1 year ago ·
2532
F9fb02a19dfbccec838f24e1cdc90477

@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 ·
2679
47923b1f334d8e3f7a00506ac3c7a636

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 ·
5840
6883e5ef03484d4fcef507d7b4f1d243

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 ·
10508
28e525370a85365222406b90c7c57884

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 ·