简体   繁体   中英

localStorage: Storing data individually VS one big String?

I want to keep multiple tallies in localStorage. Is it more efficient to store and retrieve several small data, or one big one?

Eg. this:

localStorage.setItem('id1', tally1);
localStorage.setItem('id2', tally2);

for(var i=0; i<tallyIds.length; i++){
    this.tallies.push(tallyIds[i], localStorage.getItem(tallyIds[i]));
}

Or this:

localStorage.setItem('tallies', '[{"id1": tally1}, {"id2": tally2}"]');
this.tallies = JSON.parse(localStorage.getItem('tallies'));

I know some devices will automatically clear some data from localStorage periodically. So, storing each one separately might be advantageous, in the case where perhaps only some will be lost when this happens - but if stored all in one big string, then if/when the device decides to clear it, all is lost.

However, is looping through the entire list (only a few hundred items) going to be way slower?

Almost certainly you should prefer to store the tallies as an array under a single key. If localStorage is cleared, storing the tallies independently

a. isn't likely to save any of them (the cmd localStorage.clear(), for instance will purge everything) b. could lead to confusing situations where you aren't sure if all your data is really intact or only some of it was lost.

On the plus side, storing the tallies as an array means you can filter, map, sort and reverse them among other operations very easily.

For your particular case it would probably be easier to store the tallies in one localStorage key and value (as a big string) and use JSON parse to reconstruct your object, add to it, then stringify it again. It would be easier than splitting it up by each tallies to different keys.

If you don't have so many data layers that you really need a real local database like IndexedDB, a single key and a JSON string value is probably OK in that case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM