python eval vs ast.literal_eval vs JSON解码 [英] python eval vs ast.literal_eval vs JSON decode
问题描述
我正在将 2 MB 的数据作为字符串转换为 dict.输入以 JSON 序列化.
I am converting 2 MB of data as a string into a dict. The input is serialized in JSON.
无论如何,我目前正在使用 ast.literal_eval 并且我得到了我想要的字典,但是当我尝试只运行 eval 时,它似乎运行得更快,并且还返回相同的结果.
Anyways I am currently using ast.literal_eval and I get the dictionary I want, but then when I tried just running eval it seems to run faster, and also returns the same result.
当 eval 工作正常时,是否有任何理由使用 ast 模块或 json 模块?
Is there any reason to use the ast module or the json module when eval works just fine?
推荐答案
我真的不喜欢在 stackoverflow(和其他地方)上的这种态度在没有任何上下文的情况下告诉人们他们正在做的事情是不安全的,他们不应该这样做.也许只是一个一次性的脚本来导入一些数据,那么为什么不选择最快或者最方便的方式呢?
I don't really like this attitude on stackoverflow (and elsewhere) telling people without any context that what they are doing is insecure and they shouldn't do it. Maybe it's just a throwaway script to import some data, in that case why not choose the fastest or most convenient way?
然而,在这种情况下,json.loads
不仅更安全,而且速度提高了 4 倍以上(取决于您的数据).
In this case, however, json.loads
is not only more secure, but also more than 4x faster (depending on your data).
In [1]: %timeit json.loads(data)
10000 loops, best of 3: 41.6 µs per loop
In [2]: %timeit eval(data)
10000 loops, best of 3: 194 µs per loop
In [3]: %timeit ast.literal_eval(data)
1000 loops, best of 3: 269 µs per loop
如果你认为 json 是一种比 python 更受约束的语言/格式,那么使用优化的解析器解析它必须更快.
If you think about it makes sense json is a such more constrained language/format than python, so it must be faster to parse with an optimized parser.
这篇关于python eval vs ast.literal_eval vs JSON解码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!