Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js: does JSON.parse block the event loop?

Tags:

json

node.js

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 ?

like image 888
Gal Ben-Haim Avatar asked Sep 17 '13 06:09

Gal Ben-Haim


1 Answers

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.

like image 128
Alex Wayne Avatar answered Sep 27 '22 21:09

Alex Wayne