by Tade0 · 7y ago · 0 comments
A good rule of thumb is to apply this technique for objects of 10 kB or larger — but as always with performance advice, measure the actual impact before making any changes.
Although it may still not be worth it. At work I have this hand-rolled utility for mocking the backend using a .har file(which is a JSON). I use it to reproduce bugs found by the testers, who are kind enough to supply me both with such a file and a screencast.
On a MacBook Pro a 2.6MB .har file takes about 140ms to parse and process.
I worked on an app a while ago which would have to parse 50mb+ JSON objects on mobile devices. In some cases (especially on mid-range and low-end devices) it would hang the main thread for a couple seconds!
So I ended up using a library called oboe.js [1] to incrementally parse the massive JSON blobs putting liberal `setTimeout`'s between each step to avoid hanging the main thread for more than about 200ms at a time.
This meant that it would often take 5x longer to fully parse the JSON blob than just using `JSON.parse`, but it was a much nicer UX as the UI would never hang or freeze during that process (at least perceptively), and the user wasn't waiting on that parsing to happen to use the app, there was still more user-input I needed from them at that time. So even though it would often take 15+ seconds to parse now, the user was often spending 30+ seconds inputting more information, and now the UI would be fluid the whole time.
It is length prefix encoded format so it’s pretty safe to work in a streaming manner too.
https://code.fb.com/android/improving-facebook-s-performance...
side note: legit question, I don't do web/app dev
So even if you put it behind a promise, when that promise actually runs, it will block the thread.
In essence, using promises (or callbacks or timeouts or anything else like that) allows you to delay the thread-blocking, but once the code hits `JSON.parse`, no other javascript will run until it completes. And since no other javascript will run, the UI is entirely unresponsive during that time as well.
[1] Technically there are web-workers, and I looked into them to try and solve this problem. Unfortunately any complex-objects that get sent to or from a worker need to be serialized (no pass-by-reference is allowed except for a very small subset of "C style" arrays called TypedArrays). So while you could technically send the string to a worker and have the worker call `JSON.parse` on it to get an object, when you go to pass that object back the javascript engine will need to do an "implicit" `JSON.stringify` in the worker, then a `JSON.parse` in the main thread. Making it entirely useless for my usecase.
But continuing with that same thought process, I very nearly went for an architecture that used a web-worker, did the `JSON.parse` in the worker, then exposed methods that could be called from the main thread to get small amounts of data out of the worker as needed. Something like `worker.getProperty('foo.bar.baz')` which would only take the parsing hit for very small subsets of the data at a time. But ultimately the oboe.js solution was simpler and faster at runtime.
If you have a large json object. You can use the fetch api to work with it. If you need to cache it, use the cache storage api. Unlike localStorage which will freeze the UI, cache storage wont.
It’s slightly slower since it needs to talk to another thread but who cares as long as the UI is responsive to do other things.
http://oboejs.com/examples#demarshalling-json-to-an-oop-mode...
I could see the value in this for sure. I currently have a problem of loading a ton of JS for some users who have thousands of objects embedded in the view with Rails using toJSON() in a <script>. It’s creating far too much weight on the frontend. I’ve been considering fetching it via a simple REST request instead.
I think of js entirely from a node.js perspective where I conceptualize it as an async task. Is this also wrong?
[0]: There is now the Web Workers API which does allow you to run code in the background. I've never used it, but I have heard that it has a pretty high overhead since you have to communicate with it through message passing, so it's possible you wouldn't actually gain anything by using it to parse a large JSON object.
https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers...
I believe you'd use Workers (WebWorkers?) https://developer.mozilla.org/en-US/docs/Web/API/Workers to actually do it off the main thread entirely inside JS.
You could try to use a web worker, but then you run into the problem that they don't have shared memory, so you need to pass data back some other way.
What was the memory overhead for the application?
And I did originally plan on using something like a websocket, but turns out with some minor changes on the server side we could start streaming data while it was still being gathered, and oboe.js is actually able to start parsing data even while it's still downloading from a normal XHR request, and is designed to be as efficient as possible (so it throws away string data as soon as it's not needed any more).
So there weren't really any additional benefits to be had from using websockets and breaking it up into multiple distinct requests would probably have been slower!
(I just realized I forgot to add a link to oboe.js! But I highly recommend it. It seems it's just gotten better since the last time i've used it)
It was a system where the goalposts moved many times during the development. If I were to do it again, I wouldn't use JSON, but after having the goals change a few times and then having the original server-side components get co opted to work on other projects, it was hard to justify the time that would be spent switching to a different, more appropriate wire format.
Example fibonacci worker code that doesn't block the UI, even at larger calculations
const fib = n => (n < 2 ? n : fib(n - 1) + fib(n - 2))
onmessage = msg => {
console.log('fibonacci worker onmessage', msg)
postMessage({ num: msg.data, result: fib(msg.data) })
}
[1] https://github.com/bharathnayak03/react-webworker-hookSo passing a string to a worker and having it JSON.parse it works great. But when you go to pass that object back to the main thread, it implicitly does a JSON.stringify and a JSON.parse back on the main thread (technically it's called a "Structured Copy", but it's mostly the same thing), putting you in the exact same situation.
Why? Because a large JSON structure is most probably just a large JSON structure, but you most probably don't need it as a whole. You may need a total count of items, you may need a paginated set of items, or only a certain item or a set of fields of items — well, an API.
Except funnily enough JSON.stringify + JSON.parse is usually recommendation as it's either comparable or faster than the structured copy the engine itself does :/
Web workers are depressingly bad...
It also allows you to overlay local files, so you can change code while reusing server responses.