Performance Benefits of Using Immutable Objects in Scripting Languages

interpretersperformancePHPpython

As I understand it, writing your objects in an immutable style can help the performance of your program for compiled languages, as the compiler tends to rewrite your code in single static assignment form under the hood anyway.

Is there a performance benefit to using immutable objects in an interpreted language like Python or PHP?

I understand there may be readability or code quality benefits from immutability, but I am asking specifically about performance.

Best Answer

In CPython, allocation of tuples (basically immutable lists) can be slightly faster than an allocation of the equivalent mutable type with the same items. I vaguely remember similar rumors about immuable sets, but timeit didn't confirm it. Tuples can also be smaller than lists, from a few bytes to 50% (if you hit a spot where the list had to resize, and doubled its capacity to speed up future growth). Moreover, tuples and sets are - in some contexts - subject to peephole optimizations which allow creating the object once and re-using it instead of re-building it every time.

But that's mostly peanuts. It's not why we use these types, at least usually. If ever, these differences are only invoked when seriously optimizing. It's not an aspect I usually consider when deciding for either, especially since there are other benefits, not to mention the enormous semantic impact.