Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Performance enhancements #18

Merged
merged 4 commits into from Aug 27, 2018
Merged

Performance enhancements #18

merged 4 commits into from Aug 27, 2018

Conversation

maxwellgerber
Copy link
Contributor

@maxwellgerber maxwellgerber commented Aug 14, 2018

A few minor performance enhancements

  • Don't look in the cacheStore on every function call, keep in local variable
  • Don't recreate setData function on every function call
  • Set a default key for when args is empty instead of calling JSON.stringify
  • Calculate some parameters for maxAge logic ahead of time

Results:
8.3x speedup for empty arguments
1.86x speedup for single arguments
1.1x speedup for complex arguments

Benchmark Code:

const mp = require('./perf');
const m = require('./index');

const argSets = [
  [],
  [0],
  ['foo', 'bar', 'baz'],
  [{foo: true}, {bar: false}]
];

const scenarios = [
  {
    mem: mp,
    name: 'Perf    ',
  },
  {
    mem: m,
    name: 'Original'
  }
];

const N = 1e8;

for (let args of argSets) {
  for (let {mem, name} of scenarios) {
    let i = 0;
    const f = () => i++;
    const memoized = mem(f);
    const title = `${name} - with args: ${JSON.stringify(args)}`;

    console.time(title);
    for (let i = 0; i < N; i++) {
      memoized.call(memoized, ...args)
    }
    console.timeEnd(title);
  }
}

Results:

Perf     - with args: []: 3929.611ms
Original - with args: []: 32624.623ms
Perf     - with args: [0]: 5355.543ms
Original - with args: [0]: 9960.462ms
Perf     - with args: ["foo","bar","baz"]: 44711.881ms
Original - with args: ["foo","bar","baz"]: 49462.724ms
Perf     - with args: [{"foo":true},{"bar":false}]: 66376.395ms
Original - with args: [{"foo":true},{"bar":false}]: 75006.349ms

@sindresorhus sindresorhus changed the title Performance Enhancements Performance enhancements Aug 27, 2018
@sindresorhus
Copy link
Owner

Very nice! Thanks for doing this :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants