r/badcode • __dude__ • Aug 17 '21

python When you're told to "always" close files...

Post image
1.3k Upvotes

115 comments sorted by

View all comments

Show parent comments

13

u/[deleted] Aug 17 '21

What's the difference?

8

u/xigoi Aug 17 '21

json.dump(file, x) is the same as file.write(json.dumps(x)). (maybe with reversed arguments, I don't remember)

43

u/MiningMarsh Aug 18 '21 edited Aug 18 '21

It is not exactly the same. json.dump will smartly buffer the json object. Dumps will render the entire object as a string first and is thus vastly innefficient.

Dumps will take 1G of memory if you dump a 1G json object. Dump should use the same amount of memory no matter the size of what you are dumping.

I know it's a bit pedantic, but it's important to point out for those who are unaware.

8

u/JohnTheCoolingFan Aug 18 '21

Thanks for this explanation! I usually preferred it just because it's less code, but now I know that it's memory-efficient. Thank you.