+ 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
10 ответов
+ 12
Try to use ~~
It's faster than floor function.
+ 11
Thanks Calvin!
Do you know if there is much of a difference between ~~ and | 0
+ 10
@calvin wow marked difference (between Math.floor() and ~~)
+ 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
+ 9
great games have great bugs! lol
+ 9
@AZTECCO I hope I don't get negative index(i) values :D -> I would be off map!
(mapWidth and cellSize are static)
+ 6
Check out the test report
https://goo.gl/odTTzL
+ 4
I suppose so.
+ 2
so much win for this useful thread! *pickard-meme*
thank you.
+ 1
~~2/3 is equivalent and faster than math.floor (2/3)