This is for Python 3.6.
Edited and removed a lot of stuff that turned out to be irrelevant.
I had thought json
was faster than pickle
and other answers and comments on Stack Overflow make it seem like a lot of other people believe this as well.
Is my test kosher? The disparity is much larger than I expected. I get the same results testing on very large objects.
import json
import pickle
import timeit
file_name = 'foo'
num_tests = 100000
obj = {1: 1}
command = 'pickle.dumps(obj)'
setup = 'from __main__ import pickle, obj'
result = timeit.timeit(command, setup=setup, number=num_tests)
print("pickle: %f seconds" % result)
command = 'json.dumps(obj)'
setup = 'from __main__ import json, obj'
result = timeit.timeit(command, setup=setup, number=num_tests)
print("json: %f seconds" % result)
and the output:
pickle: 0.054130 seconds
json: 0.467168 seconds