logoalt Hacker News

_fluxlast Thursday at 12:33 PM3 repliesview on HN

Wouldn't ref-counting CPython already know that a has a single reference, allowing this optimization without needing any particular smart JIT?


Replies

zbentleylast Thursday at 1:27 PM

I think GP was talking about optimizing away the O(N) call on the last line. The GC will take care of removing the reference to the old (mutable) dict, but constructing a new frozendict from a mutable dict would, in the current proposal, be an O(N) shallow copy.

There are also potentially other optimizations that could be applied (not specific to dict/frozendict) to reduce the memory overhead on operations like "a = f(a)" for selected values of "f".

zahlmanlast Thursday at 1:33 PM

First thought: I would very much expect it to be able to do this optimization given the similar things it does for string concatenation.

But actually, I suspect it can't do this optimization simply because the name `frozendict` could be shadowed.

tracnarlast Thursday at 8:10 PM

Indeed, the Tcl implementation does this so e.g. `set d [dict] ; dict set d key value` can modify d in place instead of creating a copy (since everything is immutable).