Node.js:JSON.parse是否会阻止事件循环? [英] Node.js: does JSON.parse block the event loop?

查看:102
本文介绍了Node.js:JSON.parse是否会阻止事件循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用JSON.parse是将JSON字符串解析为JavaScript对象的最常用方法.

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) ?

是否有一种简单的方法来异步解析JSON?几KB-几百KB的JSON数据到底有关系吗?

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

推荐答案

在返回值之前不接受回调块的函数.所以是的,它JSON.parse阻止了.但是,解析JSON是一项占用大量CPU的任务,而JS是单线程的.因此,解析将不得不在某个时候阻塞主线程.异步仅在等待另一个进程或系统时才有意义(这就是磁盘I/O和网络之所以具有良好的异步意义的原因,因为它们比原始CPU处理具有更多的延迟).

A function that does not accept a callback blocks until it returns a value. So yes it JSON.parse blocks. But 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).

我首先证明解析JSON实际上是您的应用程序的瓶颈,然后再开始对其进行优化优化.我怀疑不是.

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.

这篇关于Node.js:JSON.parse是否会阻止事件循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆