For the most part, the two methods are equivalent, however there is one important difference. json.dump
can iterate over your data and write it out the file as it iterates, where as json.dumps
must return a complete string for you to write to the output:
import json
values = list(range(1000000))
with open("test.json", "w") as f:
# Maximum resident set size (kbytes): 62960
# f.write(json.dumps(values))
# Maximum resident set size (kbytes): 46828
json.dump(values, f)
In some extreme cases, this will cause more memory usage, which could cause problems if you're ever in a resource constrained situation.
Best to avoid the issue unless you have a compelling reason to use json.dumps
to output to a file.
dump
(orwith open
anddump
) asynchronous or will thedump
(orwith open
anddump
) completely finish executing before moving onwards in the script? – Allout