Skip to content

Instantly share code, notes, and snippets.

@jussi-kalliokoski
Created May 9, 2011 06:24
Show Gist options
  • Save jussi-kalliokoski/962137 to your computer and use it in GitHub Desktop.
Save jussi-kalliokoski/962137 to your computer and use it in GitHub Desktop.
A faster replacement for modulo in most cases, use when applicable and while the JS engines haven't optimized the native.
function modulo(dividend, divisor){
while (dividend >= divisor){
dividend -= divisor;
}
return dividend;
}
@jussi-kalliokoski
Copy link
Author

You're right, it does get cached in modern JS engines, such as with V8's Crankshaft. I thought of that, but with variance in array and random performance, I wanted to isolate the test. And the results actually go hand in hand with real life metrics, such as how many oscillators I can run simultaneously, there was a significant change when I removed that premature optimization from my code.

Thanks for the tip, but usually if I want smaller code, I use ~~ num to floor, but with the current speed of binary operations, in JS, I'll rather use the operation dedicated for the purpose when I'm doing something that gets iterated often.

What I said doesn't - however - make your test case any less interesting. It's especially interesting how V8 is best at function calls, but SpiderMonkey is much much faster when you're doing a lot of stuff without much repetition. Chrome is also terrible at handling large strings, and stuff mostly crashes when you have 100k or more memory used by JS, independently of how much memory the computer has.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment