+ 15

Is Math.floor() slow?

Hi! I have been playing around with javascript and canvas and had to use Math.floor() in a loop and found it a little slow. This was the code snippet: y = Math.floor(i / this.mapWidth) * this.cellSize; x = Math.floor(i % this.mapWidth) * this.cellSize; I changed it to this (bitwise): y = ((i / this.mapWidth) | 0) * this.cellSize; x = ((i % this.mapWidth) | 0) * this.cellSize; Is it Math.floor() that is slow? Or is my code all kinds of screwy (odd)? If it is ok? Is there a faster method to simulate integer type behaviour in javascript? FullCode: https://code.sololearn.com/W8lXKj40Vkqu/#html Lines: 74, 75

20th Nov 2017, 2:22 PM
jay
jay - avatar
10 Answers
+ 12
Try to use ~~ It's faster than floor function.
20th Nov 2017, 2:56 PM
CalviŐ˛
CalviŐ˛ - avatar
+ 11
Thanks Calvin! Do you know if there is much of a difference between ~~ and | 0
20th Nov 2017, 3:03 PM
jay
jay - avatar
+ 10
@calvin wow marked difference (between Math.floor() and ~~)
20th Nov 2017, 3:06 PM
jay
jay - avatar
+ 9
good question! in cpp you can cast to int and it's really faster but results are different for negative. Idk in what you can do in js, hope someone come and tell us! I'm interested
20th Nov 2017, 2:22 PM
AZTECCO
AZTECCO - avatar
+ 9
great games have great bugs! lol
20th Nov 2017, 2:28 PM
AZTECCO
AZTECCO - avatar
+ 9
@AZTECCO I hope I don't get negative index(i) values :D -> I would be off map! (mapWidth and cellSize are static)
20th Nov 2017, 2:28 PM
jay
jay - avatar
+ 6
Check out the test report https://goo.gl/odTTzL
20th Nov 2017, 3:04 PM
CalviŐ˛
CalviŐ˛ - avatar
+ 4
I suppose so.
20th Nov 2017, 2:21 PM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 2
so much win for this useful thread! *pickard-meme* thank you.
21st Nov 2017, 10:18 AM
Kustaa
+ 1
~~2/3 is equivalent and faster than math.floor (2/3)
2nd Jan 2018, 11:26 AM
Jean-Philippe Czs
Jean-Philippe Czs - avatar