unistore icon indicating copy to clipboard operation
unistore copied to clipboard

Micro-optimize action binding by preallocating arguments array

Open aduth opened this issue 6 years ago • 2 comments

It doesn't seem I can easily edit or fork the referenced benchmark, but in the latest Chrome (78), this appears to perform slightly better than the current implementation:

image

Benchmark details Setup:
const store7 = createStore();
let viaPreallocated = (function viaPreallocated(store, action) {
    return function() {
        let args = new Array(arguments.length + 1);
        args[0] = store.getState();
        for (let i=0; i<arguments.length; i++) args[i+1] = arguments[i];
        return a7(args);
    };
})(store7, 'viaPreallocated');

Test:

viaPreallocated('a');
viaPreallocated('b');
viaPreallocated(1, 2);
viaPreallocated({});

It's a technique we use in our state library's selector binding.

The size bump is bigger than expected, not significant, but enough to fail tests without adjusting the permitted bundle size.

aduth avatar Nov 07 '19 05:11 aduth

I managed to reclaim a few bytes in 5f4fbdb by switching to a while loop.

  full/preact.js dist/unistore.js preact.js
master 760b 355b 546b
eeec990 777b 373b 546b
5f4fbdb 773b 366b 546b

I tried a few other ideas (unsuccessfully) as well:

  • Trying to attain the optimization from length assignment while avoiding explicit assignment of state.
let args = [ state ];
args.length = arguments.length;

This regressed on the benchmarked gains. I assume it's because the benefit comes from the constructor of an array with length.

  • Moving ret assignment to the top of the function.

Interestingly, this uses 2 fewer characters before gzip, but ultimately results in a larger gzipped bundle size (diff).

aduth avatar Nov 12 '19 18:11 aduth

@aduth hello stranger. i opened a couple of pull requests with rather substantial changes that i personally think greatly improves unistore and was looking for some feedback on. i'm assuming @developit is busy and meanwhile i was hoping to get this feedback from elsewhere. since you have opened a pull request yourself i assume you are familiar with the package and would love to hear what you think about the changes i propose. you can find them at https://github.com/developit/unistore/pull/182 and https://github.com/developit/unistore/pull/183. the second one builds upon the changes from the first.

lkmill avatar Dec 27 '19 06:12 lkmill