Let's assume that you are talking about using JSON versus a custom format (using MIME type text/plain
) for passing structured data.
Performance may be broken down into different components; e.g.
- 将内容编码为格式所需的相对时间,
- relative time taken to decode the format to give you the original content, and
- 编码内容的相对大小.
理论上,我们可以说,假设优化设计和实现的自定义格式不会比JSON慢,也不会比JSON密度低.("证据"是显而易见的. Select JSON的最佳实现,并对格式进行一些不会影响性能的微小更改.)
但实际上,您必须比较实际格式和实际实现的性能.因此,答案是性能实际上取决于您在设计和实现格式及其相关编码/解码软件方面做得有多好.此外,这还取决于如何实现JSON.有许多具有不同性能特征的服务器端JSON库,以及将数据从"本机"数据 struct 映射到"本机"数据 struct 的不同方式.
这让我们看到了JSON(和XML)相对于自定义格式的真正优势.
With JSON and XML, there are libraries available for any mainstream language you chose to use to assist in encoding and decoding content. With a custom format, you have to roll your own encoding / decoding for the client and server sides.
With JSON and XML, there are standards that say what is well-formed that allow other people to implement encoders / decoders. With a custom format, you have to write the specification yourself if you want other people to be able to implement your format.
- JSON和XML具有处理字符集编码和数据中出现的"元"字符等问题的标准方法.有了风俗习惯,你必须自己理解和解决这些问题.(如果你不这样做,你很可能会在赛道上遇到困难.)
易变易变.发展基于JSON/XML的格式是一件相对简单的事情.但是使用自定义格式,您(至少)有更多的工作要做,并且根据您的设计 Select ,这可能非常困难.
For most application, these issues matter far more than performance. And that's why JSON or XML are widely used.
FOLLOWUP个
但是,如果相反,您假设我没有使用自定义实现,并将发送MIME类型为text/Plain的JSON与MIME类型为application/json的发送JSON进行比较,会发生什么呢?
Then the answer is that it makes almost no performance difference.
- 您可以在HTTP请求或响应头中节省6个字节,因为MIME类型字符串较短,但对于大小以数千字节为单位的典型HTTP消息来说,这并不重要.
- Using a "text/plain" content type makes no difference to the work that needs to be done to encode / decode the request or response messages ... apart from the time taken to compare / copy 6 extra bytes, which is probably too small to measure.
In addition, using an inaccurate MIME type is (arguably) a violation of the HTTP specs. If you do this:
it is more likely that the receiver will mishandle the response; e.g. fail to decode it, or show it in a browser window, and
假设客户端或服务器使用HTTP内容类型协商,则可能会中断该协商.
In short, I can think of no good reason to do this1, and a few good reasons not to do it.
1 - In general. Obviously, there will be edge cases ...