Just made a small benchmark. What i plan to do is to get some data from localStorage quite often and i wondered will it block. While localStorage.getItem is synced operation it may sound scary but is it?
- 1st test to call 1 million times localStorage to get item which does exist.
- 2nd test to call 1 million times localStorage to get item which does NOT exist.
Results:
“Item found: 0.0007991071428571318ms per call”
“Item not found: 0.0006365004639793477ms per call”
In short – just use it. It takes no time. 0.0007 of 1 millisecond.
let results = [];
let sum = 0;
localStorage.setItem('foo', 'foo bar baz foo bar baz foo bar baz foo');
for (let i = 0; i < 1000000; i++) {
let a = performance.now();
localStorage.getItem('foo');
let result = performance.now() - a;
sum += result;
results.push(result);
}
console.log(`Item found: ${sum / results.length}ms per call`);
results = [];
sum = 0;
for (let i = 0; i < 1000000; i++) {
let a = performance.now();
localStorage.getItem('bar');
let result = performance.now() - a;
sum += result;
results.push(result);
}
console.log(`Item not found: ${sum / results.length}ms per call`);