dchest / tweetnacl-js

Port of TweetNaCl cryptographic library to JavaScript
https://tweetnacl.js.org
The Unlicense
1.75k stars 292 forks source link

Performance in Firefox #202

Closed m90 closed 3 years ago

m90 commented 3 years ago

This is not an issue, but a question rather: I am looking for ways to speed up my (symmetric) crypto heavy application that needs to decrypt a lot (think 25k at a time) of (short) messages. The application is currently using window.crypto to do that.

I now tried to benchmark the performance of window.crypto against tweetnacl-js, but I am kind of puzzled by the results:

When I decrypt 25k random messages in Chrome, tweetnacl-js will be about 4 times (maybe even more) faster than window.crypto. Yet, when I run the same benchmark in Firefox, tweetnacl-js will be about 10 times slower than window.crypto. The results for window.crypto in Firefox will be around the same speed as when run in Chrome.

My question therefore is: Is this expected / known behavior? Or is it me doing something wrong in my benchmark / usage of the library? In case not, how can I debug this further to find out why Firefox is so slow?

I am running Chrome 84.0.4147.105 and Firefox 79.0 on Ubuntu 18. This is the benchmark I am running: https://gist.github.com/m90/783da7a81a74a59644a52d4f09bd9dfd which right now prints:

web crypto: 482.926025390625ms
tweetnacl: 116.85986328125ms

in Chrome and

web crypto: 453ms
tweetnacl: 4648ms

in Firefox.

dchest commented 3 years ago

Hard to say exactly why tweetnacl is so much slower in Firefox for this benchmark. Perhaps, it throttles it somehow or maybe there’s JIT bug in this FF version. For long messages, on AES-instruction backed hardware, WebCrypto should be faster, the slowness is due to promise/async and C++<>JS overhead.

dchest commented 3 years ago

On https://tweetnacl.js.org at the bottom there are links to some benchmarks and I don’t see such huge differences between browsers on them.

m90 commented 3 years ago

Hmmm, after some more digging this seems to be interesting, but I can't really understand why:

Probably not something this library can do anything about it, but rather some performance optimization voodoo gone wrong in Firefox?

dchest commented 3 years ago

Yeah, looks a JIT issue to me: perhaps, not enough of run time for the function to trigger optimization when it's called with short messages. Unlikely to be possible to fix in the library.