How do I efficiently add items to an array in the

2019-04-07 22:25发布

问题:

From what I understand, if you want to have an array stored in the Chrome Storage API to which you want to continually add items, you need something like this:

function addToHistory(url) {
    chrome.storage.sync.get('history', function(obj) {
        var history = obj.hasOwnProperty('history') ? obj.history : [];
        history.push(url);
        chrome.storage.sync.set({'history': history}, function() {
            if (chrome.runtime.lastError)
                console.log(chrome.runtime.lastError);
            else
                console.log("History saved successfully");
        });
    });
}

This code bothers me; loading and then saving the same array every time you push a single item onto the end is horribly inefficient (especially if your history array starts getting several thousand entries).

Is there a more efficient way of doing this? I'm assuming I'm not the first to want to push to an array, so is there already a recommended way of achieving this?

回答1:

I don't think that chrome.storage.sync API is ideal for what you need. Basically this API is great for remembering user preferences or simple and short data. Sync API have limitations for usage like: - 102.4 KB for all data kept in the storage - 8 KB of data per item - 1,800 writes per hour

So if you planning to use this API to store some historical data the app may exceed limits very fast.

I'm assuming you are developing an extension, not the app. In app you have access to the chrome.syncFileSystem API which may be used to save syncable data in a file.

Answering your question there's no one way to optimize your function. You can try to store the data periodically - for example every 30 seconds or so. You just need to remember to save data after a user closes the app.

You can also store this value as a variable in memory and save it when the user leave the screen or close the app but it is dangerous because the app may close before asynchronous task complete.

Anyway I think that this API is not the best solution for your app.