r/javascript • • Jan 31 '15

It's 2015, why the hell is JSON.parse synchronous?

There is no standard JavaScript API for asynchronous JSON parsing in the browser. Does anyone know why? It seems like such an obvious feature and I can't find a decent explanation for its absence.

And before anyone chimes in with Web Workers; they are not the answer. Posting a large JavaScript object to the main thread from a Web Worker is a blocking operation, just like JSON.parse.

0 Upvotes

39 comments sorted by

39

u/notunlikethewaves Jan 31 '15

Because parsing json is entirely cpu bound.

12

u/Bieb Jan 31 '15

This. I don't believe most people have a grasp on how exactly the event loop works and why certain operations are async in the first place. You can't just wave a magic wand and make something work asynchronously (in javascript).

1

u/realityking89 Jan 31 '15

Well making it asynchronous would allow browsers to process it off the main thread. So while an async API in itself won't necessarily help, it might help browser optimise better. However since most likely a lot of objects would need to be created that might not be feasible.

2

u/billy_tables Feb 03 '15

it might help browser optimise better

Optimise what better?

2

u/realityking89 Feb 04 '15

Async work can be executed off the main thread, but that's the reason the Web Crpto API is all async.

1

u/bwaxxlo tckidd Jan 31 '15

You could use things like setTimeout(fn, 0), right? That ensures your code is pulled outside the main call stack. That's as far as I can imagine one creating an async function.

8

u/nschubach Feb 01 '15 edited Feb 01 '15

You just make it take longer... setTimeout doesn't create another thread, it just puts the call in another queue that is periodically checked for occurances.

Edit: I feel this need expanding. You can think of intervals and timeouts in JavaScript as a secondary stack. If you add a timeout, JS places that call in a queue and will wait for a free moment to pull off an item to process. If you setTimeout your parse method, all you do is delay execution. When the VM has a spare second, it will pull off the request at that time and process it. It still runs in the same process and will tie up the interface for the same period of time. It just does it later.

0

u/[deleted] Feb 01 '15

[deleted]

2

u/nschubach Feb 01 '15

When the timeout is called, the code is then moved back into the stack and it will run 100% at that time. The only way to use setTimeout to push the processing back would be to not rely on the built in parser and write your own that delays on a regular basis. Every time the timeout is called, that code is pushed back on the stack.

2

u/jsgui Feb 01 '15

Allowing async JSON parsing would be an easy route to paralleling some of the tasks. It makes sense in some cases to offload a large task like this to a different process or thread that does not block the UI.

While web workers seem like an answer to how this could be done, having a standard method that would efficiently parse (or stringify) in a separate threat would be a feature I would probably find effective.

12

u/[deleted] Jan 31 '15

Parsing enough JSON to have a visible effect on the UI thread is a pretty rare use case no? Still why don't you come up with something and maybe it will catch on

2

u/zhay Full-stack web developer (Seattle) Jan 31 '15

The problem is that you can't just come up with something and release it to the world. JavaScript is single threaded (with the exception of web workers), so you would need the browser to implement an asynchronous JSON API. To do this, you would need to influence the next version of JS.

3

u/KirbzStar Jan 31 '15

with the exception of web workers

Isn't that just the answer then if you did need async json parsing?

5

u/jcready __proto__ Jan 31 '15

No, because objects need to be serialized before being sent to/from different contexts.

4

u/TMiguelT Feb 01 '15

Oh so is the problem that the web worker would parse the JSON fine but then stringify it to send it back to the main thread, reversing the whole process?

6

u/holloway Feb 01 '15

Exactly.

3

u/jcready __proto__ Feb 01 '15

Essentially. Objects cannot be shared across contexts because of concurrency issues.

6

u/[deleted] Feb 03 '15

Posting a large JavaScript object to the main thread from a Web Worker is a blocking operation, just like JSON.parse.

Have you tried using Servo? It has strong type and memory safety guarantees from being in Rust-lang, which means its JS engine should be able to properly dispatch asynchronous string parsings necessary to async your JSON. If that isn't enough, you can probably write a plugin that uses Rust channels so the threads can work the async out. I mean, really, when you're scaling, you just want to get things like that out of the way and scale.

5

u/jcready __proto__ Jan 31 '15

It's a good question why there isn't at least an option to do it asynchronous. But for 99.9% of the use cases it's probably unnecessary. I mean, I'd like an async Array.sort() method too, but for most use cases it would be overkill.

8

u/ogrechoker Jan 31 '15

Mozilla looked into this and found unless the array was ridiculously large, it wasn't worth the performance gain

1

u/jcready __proto__ Jan 31 '15

Right, but what do I do in those situations?

1

u/recompileorg Feb 01 '15

If all you want to to keep form locking the UI, an easy solution is to just treat it like an animation. Do just a little bit at a time until the entire operation is complete. Depending on the type of sort, this should be trivial. It will slow down your sort a good bit, but I suspect that the trade-off will be worth it most of the time.

I did exactly that for an intro class I was teaching, though I also included an actual animation. (The whole point was to let students see each step in the sort as it happened.) You'll probably want to complete more of the sort on each "frame" than a single operation like I did.

0

u/[deleted] Jan 31 '15

[deleted]

1

u/ogrechoker Feb 01 '15

it is usually a chore to structure the computation to get that speedup. "Casual" use of PJS with that API will not be useful in many cases; "nobody" with some random array that they're currently mapping would benefit from mapping it in parallel.

https://groups.google.com/forum/#!msg/mozilla.dev.tech.js-engine/H-YEsejE6DA/u2gRBnsGwM0J

1

u/[deleted] Feb 05 '15

I'd like an async Array.sort() method too

Does "async" mean something different than I think it does? Say I have a large user base, like 500 or more, trying to access my three Mongo shards all at once. Even with Mongo set to eventual-consistency and not worrying about confirming the writes, it's possible that during peak usage hours we could break the 200ms user-response threshold on larger sorts (say, like, you needed to parse a CSV with 1000+ lines). Is there a reason why Node doesn't have this yet?

4

u/bonafidebob Jan 31 '15 edited Jan 31 '15

Guessing that creating a lot of small objects in the heap would require a lot of overhead if parsing was done in another thread. Single threaded JS can be fast because there's no contention for heap locks. If another thread tries to create a bunch of small objects then the synchronization overhead might be on par with the parsing itself, so not much savings.

As with workers, getting the large object into the context has to be a blocking operation.

2

u/[deleted] Jan 31 '15

As with workers, getting the large object into the context has to be a blocking operation.

I believe this would be the solution to that:

http://updates.html5rocks.com/2011/12/Transferable-Objects-Lightning-Fast

6

u/jcready __proto__ Jan 31 '15

You'd have to serialize the object into an ArrayBuffer. And that serialization is the problem we're already talking about.

5

u/[deleted] Jan 31 '15

I thought the problem was the transfer but it didn't occur to me that conversion to an ArrayBuffer would be just as intensive. Doh!

2

u/altano Jan 31 '15

Every async operation is made up of small blocking operations, at some granularity. It's just a question of what the granularity is.

You can make a non-blocking, async JSON parse using a streaming JSON parser and web workers. Don't post the whole object, let it get copied in chunks, release the main event loop after every chunk. It'll have tons of overhead but it could work.

2

u/holloway Feb 01 '15

I wonder what kind of sweet-spot you'd need (in terms of JSON size) to make something like that more efficient. I'd guess that no JSON size could justify that overhead.

2

u/jcready __proto__ Feb 01 '15

It's not about the speed, it's about not blocking the main thread.

5

u/holloway Feb 01 '15

Glad I didn't use the word speed then.

2

u/holloway Feb 01 '15

I don't agree on JSON.parse, but localStorage has even less of a reason to be synchronous because it's i/o bound and disks might need to spin up to speed before any reading occurs. It's notoriously slow.

2

u/biny-fi Feb 01 '15

Split the big json to many smaller ones and parse one by one. Works much better this way.

1

u/ohbuckeye Feb 04 '15

good avice

1

u/totes_meta_bot Feb 03 '15

This thread has been linked to from elsewhere on reddit.

If you follow any of the above links, respect the rules of reddit and don't vote or comment. Questions? Abuse? Message me ^here.

0

u/Ginden Feb 01 '15

Parsing JSON can be done in WebWorker. Cost of transfering even 100MB string is neglible (few miliseconds). Strings (and other primitive/semiprimitives) are insanely cheap to copy - you can copy gigabytes of data in seconds.

1

u/Quabouter Feb 03 '15

But then you've parsed the JSON string and now you want the object back to the main thread. And how's that implemented? Exactly, by first serializing it in your WebWorker and then deserializing it in your main thread, which will take about as much time as doing the parsing in the main thread in the first place. So while it initially might seem like a good idea, it doesn't work.

1

u/Ginden Feb 03 '15

Who cares if it takes even 10 seconds? There is only one important thing - is it done asynchronously, without blocking UI thread?

1

u/[deleted] Feb 04 '15

[removed] — view removed comment

1

u/ohbuckeye Feb 04 '15

thank(you)