Are weak refs slower than strong refs?

shredwheat pete at shinners.org
Sun Feb 25 11:00:31 EST 2007


On Feb 24, 10:17 pm, John Nagle <n... at animats.com> wrote:
>    Are weak refs slower than strong refs?  I've been considering making the
> "parent" links in BeautifulSoup into weak refs, so the trees will release
> immediately when they're no longer needed.  In general, all links back
> towards the root of a tree should be weak refs; this breaks the loops
> that give reference counting trouble.

I've never really benchmarked their overhead. Thinking about how they
work, I wouldn't expect a measurable difference in the time for
dereferencing the weakrefs. But internally objects must track who all
their weak reference holders are, so that will add some cost. I am
guessing if the hierarchy is built once and remains fairly static you
won't see the cost of this management. If the hierarchy is very
dynamic there will be more weakref overhead. On the other hand, you
will be freeing up the work done by the cyclic testing in the garbage
collector.

After doing similar work with weakrefs in hierarchies, I'd say it is
worth doing. If you do the work, it would be interesting to see what
the performance looks like. Be sure there is a gc.collect() in the
timing for the  original strong-ref version. :-)




More information about the Python-list mailing list