What is the difference between json.dump() and json.dumps() in python?

前端 未结 4 1177
遥遥无期
遥遥无期 2020-12-04 08:15

I searched in this official document to find difference between the json.dump() and json.dumps() in python. It is clear that they are related with file write option.
But

4条回答
  •  孤城傲影
    2020-12-04 08:34

    In memory usage and speed.

    When you call jsonstr = json.dumps(mydata) it first creates a full copy of your data in memory and only then you file.write(jsonstr) it to disk. So this is a faster method but can be a problem if you have a big piece of data to save.

    When you call json.dump(mydata, file) -- without 's', new memory is not used, as the data is dumped by chunks. But the whole process is about 2 times slower.

    Source: I checked the source code of json.dump() and json.dumps() and also tested both the variants measuring the time with time.time() and watching the memory usage in htop.

提交回复
热议问题