Daninet / hash-wasm

Lightning fast hash functions using hand-tuned WebAssembly binaries
https://npmjs.com/package/hash-wasm
Other
881 stars 49 forks source link

Slower on first run? #12

Closed AdrianoFerrari closed 3 years ago

AdrianoFerrari commented 3 years ago

Thanks for publishing this! Looks like just what I need to speed up a core/critical part of my application (https://gingkowriter.com).

I'm new to wasm, and I'm aware that this is likely not an issue with this package, but I hope you can point me in the right direction...

I've noticed that the first time I calculate a hash, it takes ~10x longer than subsequent times. I've not been able to find any specific resources to help me figure out why.

Is it an initial decode (from base64)? An initial compilation? Is it avoidable in some way? I could simply do a fake first run on app startup, so it's ready when it's next needed, but I'd like to understand what's going on more deeply.

I'm using the shorthand form for sha1, in a web app bundled with Webpack. (Can make source available).

Thanks!

Daninet commented 3 years ago

Yeah, the first run is slower, because the things you mentioned: base64 decode + WASM compilation.

Using .wasm files directly would require special webpack configuration and it can cause CORS issues. So I embedded the wasm binaries into the JS bundle as base64 strings, because it is much more portable and easier to use. After the binary is compiled it will be cached internally, thus you see better performance at the subsequent runs.

If you want to get consistent speeds, you can make a pre-initialization at page load time with a simple sha1('') call. You can also try using the createSHA1() API. At some use cases / environments it might be faster.

AdrianoFerrari commented 3 years ago

Ok, thanks for the info :slightly_smiling_face: I just wanted to make sure it was expected, and I wasn't using the package incorrectly.

Will make a sha1('') call somewhere.