I create a list of a million int objects, then replace each with its negated value. tracemalloc reports 28 MB extra memory (28 bytes per new int object). Why? Does Python not reuse the memory of the garbage-collected int objects for the new ones? Or am I misinterpreting the tracemalloc results? Why does it say those numbers, what do they really mean here?
import tracemalloc
xs = list(range(10**6))
tracemalloc.start()
for i, x in enumerate(xs):
xs[i] = -x
print(tracemalloc.get_traced_memory())
Output (Try it online!):
(27999860, 27999972)
If I replace xs[i] = -x with x = -x (so the new object rather than the original object gets garbage-collected), the output is a mere (56, 196) (try it). How does it make any difference which of the two objects I keep/lose?
And if I do the loop twice, it still only reports (27992860, 27999972) (try it). Why not 56 MB? How is the second run any different for this than the first?
from Does Python not reuse memory here? What does tracemalloc's output mean?
No comments:
Post a Comment