简体   繁体   English

localStorage:单独存储数据还是一个大字符串?

[英]localStorage: Storing data individually VS one big String?

I want to keep multiple tallies in localStorage.我想在 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.我知道有些设备会定期从 localStorage 中自动清除一些数据。 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如果 localStorage 被清除,则独立存储标签

a.一种。 isn't likely to save any of them (the cmd localStorage.clear(), for instance will purge everything) b.不太可能保存它们中的任何一个(例如,cmd localStorage.clear() 将清除所有内容) 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.对于您的特定情况,将计数存储在一个 localStorage 键和值(作为一个大字符串)中并使用 JSON 解析来重建您的对象,添加到它,然后再次对其进行字符串化可能会更容易。 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.如果您没有太多的数据层,而您确实需要像 IndexedDB 这样的真正的本地数据库,那么在这种情况下,单个键和一个 JSON 字符串值可能就可以了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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