Is there a way to minimise CPU usage by reducing number of write operations to chrome.storage?

Viewed 75

I am making a chrome extension that keeps track of the time I spend on each site. In the background.js I am using a map(stored as an array) that saves the list of sites as shown.

let observedTabs = [['chrome://extensions', [time, time, 'icons/sad.png']]];

Every time I update my current site, the starting and ending time of my time on that particular site is stored in the map corresponding to the site's key. To achieve this, I am performing the chrome.storage.sync.get and chrome.storage.sync.set inside the tabs.onActivated, tabs.onUpdated, windows.onFocusChanged and idle.onStateChanged. This however results in a very high CPU usage for chrome(around 25%) due to multiple read and write processes from(and to) storage.

I tried to solve the problem by using global variables in background.js and initialising them to undefined. Using the function shown below, I read from storage only when the the current variable is undefined(first time background.js tries to get the data) and at all other times, it just uses the set global variable.

let observedTabs = undefined;
function getObservedTabs(callback) {
   if (observedTabs === undefined) {
        chrome.storage.sync.get("observedTabs", (observedTabs_obj) => {
        callback(observedTabs_obj.observedTabs);
    });
    } else {
          callback(observedTabs);
    }   
} 

   

This solves the problem of the costly repeated read operations. As for the write operations, I considered using runtime.onSuspend to write to storage once my background script stops executing, as shown:

chrome.runtime.onSuspend.addListener(() => {
    getObservedTabs((_observedTabs) => {
        observedTabs = _observedTabs;
        chrome.storage.sync.set({"observedTabs": _observedTabs});
    });
}); 

This, however doesn't work. And the documentation also warns about this.

Note that since the page is unloading, any asynchronous operations started while handling this event are not guaranteed to complete.

Is there a workaround that would allow me to minimise my writing operations to storage and hence reduce my CPU usage?

0 Answers
Related