Save State Performance
See original GitHub issueHey, I’m have come across a minor performance issue when saving state in the subscriber. In this instance there is a simple fix available too, but I thought I would reach out to see what people think about it first.
So, you’re wanting to persist the data, without getting in the way of your code performance. Then why are we blocking the saveState
waiting for the write of data to the data storage in question.
The problem
The current implementation causes waits for localStorage
or any other storage method to block the current thread waiting until its performed its operation.
This can cause the application to become non-responsive for a moment while we’re writing this state to disk.
/* helper to simulate the delay in localStorage writing */
function wait(ms){
var start = new Date().getTime();
var end = start;
while(end < start + ms) {
end = new Date().getTime();
}
}
/* ORIGINAL blocking version */
const myPlugin = store => {
store.subscribe((mutation, state) => {
console.time('VuexSubscription')
wait(7000)
console.timeEnd('VuexSubscription')
})
}
The proposal
Make the write method asynchronous. In this example we go one more and use requestIdleCallback
in order to find some guaranteed free time and avoid jank.
/* PROPOSED non blocking version */
// Shim `requestIdleCallback`
const requestIdleCallback = window.requestIdleCallback || (cb => {
let start = Date.now();
return setTimeout(() => {
cb({
didTimeout: false,
timeRemaining() {
return Math.max(0, 50 - (Date.now() - start))
}
})
}, 1);
})
const myPlugin = store => {
store.subscribe((mutation, state) => {
console.time('VuexSubscription')
requestIdleCallback(() => {
wait(7000)
}, {timeout: 60})
console.timeEnd('VuexSubscription')
})
}
So, what do you think?
Is it absolutely important to block the main thread waiting for the data to write to the storage?
Issue Analytics
- State:
- Created 6 years ago
- Reactions:2
- Comments:5 (1 by maintainers)
Top GitHub Comments
For those coming from Google and looking for a quick patch solution.
Put this into your
store/index.js
👍 have a great day
Hey @rulrok the
merge
isdeepmerge
orlodash.merge