I read in a comment here on Stack Overflow that it is more memory efficient to do slice assignment when changing lists. For example,
a[:] = [i + 6 for i in a]
should be more memory efficient than
a = [i + 6 for i in a]
because the former replaces elements in the existing list, while the latter creates a new list and rebinds a
to that new list, leaving the old a
in memory until it can be garbage collected. Benchmarking the two for speed, the latter is slightly quicker:
$ python -mtimeit -s 'a = [1, 2, 3]' 'a[:] = [i + 6 for i in a]'
1000000 loops, best of 3: 1.53 usec per loop
$ python -mtimeit -s 'a = [1, 2, 3]' 'a = [i + 6 for i in a]'
1000000 loops, best of 3: 1.37 usec per loop
That is what I'd expect, as rebinding a variable should be faster than replacing elements in a list. However, I can't find any official documentation which supports the memory usage claim, and I'm not sure how to benchmark that.
On the face of it, the memory usage claim makes sense to me. However, giving it some more thought, I would expect that in the former method, the interpreter would create a new list from the list comprehension and then copy the values from that list to a
, leaving the anonymous list in floating around until it is garbage collected. If that's the case, then the former method would use the same amount of memory while also being slower.
Can anyone show definitively (with a benchmark or official documentation) which of the two methods is more memory efficient/which is the preferred method?
Thanks in advance.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…