dchest / scrypt-async-js

Fast "async" scrypt implementation in JavaScript
http://dchest.github.io/scrypt-async-js/
BSD 2-Clause "Simplified" License
139 stars 26 forks source link

Allow preallocating buffers, so that these can be reused in subsequent calls #34

Closed palant closed 6 years ago

palant commented 7 years ago

Currently, each scrypt() call will allocate new buffers. Depending on the cost factor, this might mean a whole lot of memory being allocated and then thrown away. When performing a number of calls with similar parameters, this approach is wasteful. There is a minor performance impact (around 10% in my tests), but it also increases memory churn and might cause memory pressure if multiple buffers happen to be alive at the same time (one cannot rely on GC to collect them timely).

Here I added an scrypt.allocate(options) function that will produce options with preallocated buffers - these options can be passed in to multiple scrypt() calls and the buffers will be reused. I had to make some changes first, otherwise things would have been unmaintainable:

I know that this isn't quite complete yet, let me know if you agree to the general direction and I will add tests and documentation changes.

dchest commented 7 years ago

Thanks. I'll think about merging it, but my other project already has an implementation which allows preallocating buffer — please take a look at @stablelib/scrypt package: docs, source. I should mention it in the readme.

palant commented 7 years ago

Thank you for pointing me to StableLib, I get identical performance in Firefox and better performance in Chrome. Still need to test on mobile but it seems that this is what I will used.