与返回原始 html 相比,json 会增加任何开销吗?
我有一个 ajax 调用,当前返回我注入到页面中的原始 html。
现在我的问题是,在某些情况下,我需要返回一个计数值以及原始 html,如果该计数 > 10、我需要触发另一个 jquery 操作以使某些内容可见。
这里最好的方法是返回 json,对吧?所以我可以这样做:
jsonReturned.counter
jsonReturned.html
你同意吗?
另外,出于好奇,json 的性能是否更昂贵?它只是一个具有属性的简单对象,但只是询问。
I have a ajax call that is currently returning raw html that I inject into the page.
Now my issue is, that in some situations, I need to return back a count value along with the raw html, and if that count is > 10, I need to fire another jquery operation to make something visible.
The best approach here would be to return json then right? So I can do:
jsonReturned.counter
jsonReturned.html
Do you agree?
Also, out of curiosity more than anything, is json any more expensive performance wise? It is just a simple object with properties but just asking.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这个问题保留了一些自由裁量权,但在我看来,返回 JSON 而不是原始 HTML 并不存在效率问题。正如您所说,您可以轻松返回多条消息,而不需要额外的解析(例如,我通常会有状态、消息和数据)。
我没有运行任何数字,但我可以告诉你,我在流量非常大(数百万个请求)的情况下通过 AJAX 使用 JSON,没有效率问题。
This question reserves some discretion, but in my opinion, there is no efficiency concern with returning JSON instead of raw HTML. As you stated, you can easily return multiple messages without the need for extra parsing (I'll often have a status, a message, and data for example).
I haven't run any numbers, but I can tell you I've used JSON via AJAX in very heavy traffic (millions of requests) situations with no efficiency concerns.
我同意,json 是要走的路。毫无疑问,这是一个性能打击。问题是:这个打击可以忽略不计吗?我的意见是可以忽略不计。如今,Javascript 在浏览器中的速度相当快。你应该没问题。
I agree, json is the way to go. There is no doubt that it is a performance hit. The question is: is it a negligible hit? My opinion is that it is negligible. Javascript is pretty fast these days in the browser. You should be ok.
JSON 可能比 HTML 更紧凑,因为括号/引号对总是比最小的可能标签组合更简洁。
{}
/[]
、""
与。在我看来,2 个字符 vs 7 个字符是胜利。但是,如果您的数据需要使用
\
进行大量转义,那么 JSON 将是净损失,并且可能会使任何给定字符串的大小加倍。JSON'll likely be more compact than HTML, since bracket/quote pairs are ALWAYS going to be terser than the smallest possible tag combos.
{}
/[]
,""
v.s.<a></a>
. 2 chars v.s. 7 is a win in my book. however, if your data requires huge amounts of escaping with\
, then JSON would be a net loss, and could double the size of any given string.额外开销的来源包括
了解这些对您的应用程序是否重要的唯一方法是测量它们。它们显然都不大,而且都不超过 O(n)。
Sources of additional overhead include
The only way to know whether these are significant to your app is to measure them. Neither of them are obviously large and none of them are more than O(n).