Skip to content

refactor(fragment_cache): reuse result#3985

Merged
SukkaW merged 1 commit into
hexojs:masterfrom
SukkaW:fragment_cache_reuse
Dec 18, 2019
Merged

refactor(fragment_cache): reuse result#3985
SukkaW merged 1 commit into
hexojs:masterfrom
SukkaW:fragment_cache_reuse

Conversation

@SukkaW

@SukkaW SukkaW commented Dec 18, 2019

Copy link
Copy Markdown
Member

What does it do?

Fix a potential performance issue introduced by #3744: After #3744, the function passed to fragment_cache might be called twice instead of once.

A PoC can be viewed here: https://runkit.com/sukkaw/5df9e053e7c3d50019810e89

const cache = {};
let called1 = 0;
let called2 = 0;

// This PR
const cacheFunc1 = (k, fn) => {
  if (cache[k] != null) return cache[k];
  
  const result = fn();
  cache[k] = result;
  
  return result;
}

// PR #3744
const cacheFunc2 = (k, fn) => {
  if (cache[k] != null) return cache[k];

  cache[k] = fn();
  const result = fn();
  return result;
}

cacheFunc1('1', () => { return called1++; });
cacheFunc1('1', () => { return called1++; });
cacheFunc1('1', () => { return called1++; });
cacheFunc2('2', () => { return called2++; });
cacheFunc2('2', () => { return called2++; });
cacheFunc2('2', () => { return called2++; });
console.log(called1, called2);
// 1 2

How to test

git clone -b fragment_cache_resue https://github.com/sukkaw/hexo.git
cd hexo
npm install
npm test

Screenshots

Pull request tasks

  • Add test cases for the changes.
  • Passed the CI test.

@SukkaW SukkaW requested a review from curbengh December 18, 2019 08:27
@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage remained the same at 97.117% when pulling 3a761d7 on SukkaW:fragment_cache_reuse into 5179a6a on hexojs:master.

@curbengh curbengh left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In light of this, I'm re-visiting #3744.

@SukkaW

SukkaW commented Dec 18, 2019

Copy link
Copy Markdown
Member Author

@curbengh I have found some similar cases introduced in #3744 as well. Should I include them in this PR?

@curbengh curbengh mentioned this pull request Dec 18, 2019
2 tasks
@curbengh

curbengh commented Dec 18, 2019

Copy link
Copy Markdown
Contributor

I just finished working on other cases introduced by #3744, in #3986

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.

3 participants