Search code examples
jsonfirefoxgoogle-chromeweb-worker

Is delegating JSON.parse to web worker worthwile (in Chrome Extension/FF Addon)?


I am writing a Chrome Extension which stores great deal of data in browser's localStorage and parses it on every page load. Now as the size of data increases, page load time/performance starts degrading. So I thought delegating the parsing to a web worker. But I am doubtful if it is worthwile. What I can do is pass my string to be parsed to worker like this.

worker.postMessage(localStorage['myObj']);

And I plan to parse this string into JSON and send it back to the main thread, like so

worker.onMessage(function(myObj){
    //Then Play around with my object here.
});

But as I googled on the performance aspect of this method, including message posting and listening overheads, and the fact that some browser's don't allow sending JSON objects in the message and some serialize it automatically while sending, I doubt if this method is worthwile.

Since my app is just a Chrome Extension and also a Firefox Addon, I am concerned with just these two browsers. Can anyone suggest me if this method is suitable for these two browsers?


Solution

  • The currently-accepted answer is simply incorrect. It's entirely feasible to do what you asked about, example below.

    Whether it's worth doing is something you'll have to check with real data in your real scenario. There's overhead associated with sending the JSON text to the worker and having it send back the parsed result (which may well involve some under-the-covers serialization, though it's probably not JSON), and modern browsers parse JSON very quickly.

    I suspect the overhead isn't worth it, but perhaps on huge JSON strings, if the browser's native serialization mechanism is either much faster than JSON or takes place on a thread other than the main UI thread, perhaps it could be.


    Example of using a worker to parse JSON:

    // This stands in for 'worker.js':
    var blob = new Blob([
      'this.onmessage = function(message) {\n' +
        'postMessage(JSON.parse(message.data));\n' +
      '};'
      ], { type: "text/javascript" });
    var workerUrl = URL.createObjectURL(blob);
    
    // Main script:
    var w = new Worker(workerUrl/*"worker.js"*/);
    w.onmessage = function(message) {
        display("Got response: typeof message.data: " + typeof message.data);
        display("message.data.for = " + message.data.foo);
    };
    
    display('Posting JSON \'{"foo":"bar"}\' to worker');
    w.postMessage('{"foo":"bar"}');
    
    function display(msg) {
        var p = document.createElement('p');
        p.innerHTML = String(msg);
        document.body.appendChild(p);
    }
    body {
      font-family: monospace;
    }

    Result:

    Posting JSON '{"foo":"bar"}' to worker
    Got response: typeof message.data: object
    message.data.for = bar