解析JSON比解析XML更快 [英] Is parsing JSON faster than parsing XML

查看:133
本文介绍了解析JSON比解析XML更快的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个复杂的JavaScript库,用于处理我公司的服务器端框架。

I'm creating a sophisticated JavaScript library for working with my company's server side framework.

服务器端框架将其数据编码为简单的XML格式。没有花哨的命名空间或类似的东西。

The server side framework encodes its data to a simple XML format. There's no fancy namespacing or anything like that.

理想情况下,我想将浏览器中的所有数据解析为JSON。但是,如果我这样做,我需要重写一些服务器端代码以吐出JSON。这很痛苦,因为我们有公共API,我无法轻易改变。

Ideally I'd like to parse all of the data in the browser as JSON. However, if I do this I need to rewrite some of the server side code to also spit out JSON. This is a pain because we have public APIs that I can't easily change.

我真正关心的是在解析JSON与XML的浏览器中的性能。关注真的有很大的不同吗?或者我应该专门去寻找JSON?有没有人对两者之间的性能差异有任何经验或基准?

What I'm really concerned about here is performance in the browser of parsing JSON versus XML. Is there really a big difference to be concerned about? Or should I exclusively go for JSON? Does anyone have any experience or benchmarks in the performance difference between the two?

我意识到大多数现代Web开发人员可能会选择JSON,我可以理解为什么。但是,我真的只对表现感兴趣。如果已经证明存在巨大差异,那么我准备花费额外的精力为客户端生成JSON服务器端。

I realize that most modern web developers would probably opt for JSON and I can see why. However, I really am just interested in performance. If there's a proven massive difference then I'm prepared to spend the extra effort in generating JSON server side for the client.

推荐答案

JSON应该更快,因为它是 JS 对象表示法,这意味着它可以被JavaScript本地识别。在GET方面的PHP中,我经常会这样做:

JSON should be faster since it's JS Object Notation, which means it can be recognized natively by JavaScript. In PHP on the GET side of things, I will often do something like this:

<script type="text/javascript">
    var data = <?php json_encode($data)?>;
</script>

有关详细信息,请参阅此处:

For more information on this, see here:

为什么每个人都为jQuery选择基于XML的JSON?

另外......你真正需要在生成JSON中加入什么额外的努力?当然你不能说你将手动构建JSON字符串?几乎每种现代服务器端语言都有将原始变量转换为JSON字符串的库。例如,PHP的核心 json_encode 函数会转换一个关联数组,如下所示:

Also...what "extra effort" do you really have to put into "generating" JSON? Surely you can't be saying that you'll be manually building the JSON string? Almost every modern server-side language has libraries that convert native variables into JSON strings. For example, PHP's core json_encode function converts an associative array like this:

$data = array('test'=>'val', 'foo'=>'bar');

进入

{"test": "val", "foo": "bar"}

这只是一个JavaScript对象(因为JS中没有关联数组(严格来说))。

Which is simply a JavaScript object (since there are no associative arrays (strictly speaking) in JS).

这篇关于解析JSON比解析XML更快的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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