15

using JSON.parse is the most common way to parse a JSON string into a JavaScript object.

it is a synchronous code, but does it actually block the event loop (since its much lower level than the user's code) ?

is there an easy way to parse JSON asynchronously? should it matter at all for few KBs - few hundred KBs of JSON data ?

2 Answers 2

16

A function that does not accept a callback or return a promise blocks until it returns a value.

So yes it JSON.parse blocks. Parsing JSON is a CPU intensive task, and JS is single threaded. So the parsing would have to block the main thread at some point. Async only makes sense when waiting on another process or system (which is why disk I/O and networking make good async sense as they have more latency than raw CPU processing).

I'd first prove that parsing JSON is actually a bottleneck for your app before you start optimizing it's parsing. I suspect it's not.

Sign up to request clarification or add additional context in comments.

3 Comments

If it is a problem (couple hundreds KB shouldn't be), check writings.nunojob.com/2011/12/….
can events be added to the event loop when its blocked? for example - callback from Redis subscribe is added to the loop while JSON.parse is running or this event is missed ?
@GalBen-Haim Yep! The event will get scheduled, but the handler must wait to be called until the run loop becomes available.
3

If you think that you might have a lot of heavy JSON decoding to do, consider moving it out to another process. I know it might seem obvious, but the key to using node.js successfully is in the name.

To set up another 'node' top handle a CPU heavy task, use IPC. Simple sockets will do, but ØMQ adds a touch of radioactive magic in that it supports a variety of transports.

It might be that the overhead of connecting a socket and sending the JSON is more intensive overall but it will certainly stop the blocking.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.