I have code that relies heavily on yaml for cross-language serialization and while working on speeding some stuff up I noticed that yaml was insanely slow compared to other serialization methods (e.g., pickle, json).

所以真正让我吃惊的是,在输出几乎相同的情况下,JSON比YAML快得多.

>>> import yaml, cjson; d={'foo': {'bar': 1}}
>>> yaml.dump(d, Dumper=yaml.SafeDumper)
'foo: {bar: 1}\n'
>>> cjson.encode(d)
'{"foo": {"bar": 1}}'
>>> import yaml, cjson;
>>> timeit("yaml.dump(d, Dumper=yaml.SafeDumper)", setup="import yaml; d={'foo': {'bar': 1}}", number=10000)
44.506911039352417
>>> timeit("yaml.dump(d, Dumper=yaml.CSafeDumper)", setup="import yaml; d={'foo': {'bar': 1}}", number=10000)
16.852826118469238
>>> timeit("cjson.encode(d)", setup="import cjson; d={'foo': {'bar': 1}}", number=10000)
0.073784112930297852

PyYaml的CSafeDumper和cjson都是用C编写的,所以这不是C与Python的速度问题.我甚至向它添加了一些随机数据,以查看cjson是否正在进行缓存,但它仍然比PyYaml快得多.我意识到yaml是json的超集,但在如此简单的输入下,yaml序列化程序怎么会慢两个数量级呢?

推荐答案

In general, it's not the complexity of the output that determines the speed of parsing, but the complexity of the accepted input. The JSON grammar is very concise. The YAML parsers are comparatively complex, leading to increased overheads.

JSON’s foremost design goal is simplicity and universality. Thus, JSON is trivial to generate and parse, at the cost of reduced human readability. It also uses a lowest common denominator information model, ensuring any JSON data can be easily processed by every modern programming environment.

In contrast, YAML’s foremost design goals are human readability and support for serializing arbitrary native data structures. Thus, YAML allows for extremely readable files, but is more complex to generate and parse. In addition, YAML ventures beyond the lowest common denominator data types, requiring more complex processing when crossing between different programming environments.

我不是YAML解析器的实现者,所以如果没有一些分析数据和大量示例,我就无法具体讨论数量级.在任何情况下,在对基准数据感到自信之前,一定要对大量输入进行测试.

Update天哪,误读了问题.:-(尽管输入语法很大,序列化仍然可以非常快;然而,浏览源代码,它看起来像PyYAML的Python级别的序列化constructs a representation graph,而Simplejson将内置的Python数据类型直接编码到文本块中.

Json相关问答推荐

Vega-Lite:文本笔画在外部

如何使用GoFr返回XML响应?

将pyspark.sql.Rowtype数据转换为Json字符串,消除Azure Databricks NB中的值

Jolt-Json转换:通过引用标识符(而不是索引)设置值

如何使用 JOLT 使用输入数组中的值和层次 struct 中的其他字段创建数组

Jolt规范:将嵌套数组中的null元素移除

使用jq根据对象中键的值查找对象

使用 TypeScript 接口时如何修复未定义错误?

Serde JSON 反序列化枚举

自定义将 struct 解组为切片映射

使用 Javascript 判断 JSON 对象是否包含值

如何使用 jackson 反序列化为 Kotlin 集合

没有很多类的 GSON 解析

在 JSON API Wordpress 上启用 CORS

验证和格式化 JSON 文件

Json.Net:用于自定义命名的 JsonSerializer-Attribute

在视图中将 .Net 对象转换为 JSON 对象

如何在 Python 中合并两个 json 字符串?

有没有办法折叠 Postman 中的所有 json 字段

Javascript:如何判断 AJAX 响应是否为 JSON