Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory difference iterating over frozen set vs set

Tags:

python

When using for x in obj notation, does iterating over a frozenset use less memory than a set? Or when is there a memory advantage to using a frozen set opposed to a set?

like image 947
TheoretiCAL Avatar asked Jul 31 '26 02:07

TheoretiCAL


2 Answers

I doubt there is going to be a significant (if any) memory savings from using frozenset over set. The reason to use a frozenset is that it is hashable, so you can use it as a dictionary key (or as an element of another set).

like image 116
BrenBarn Avatar answered Aug 01 '26 16:08

BrenBarn


Looking at the python2.7 source, the empty frozen set is a singleton and making a frozenset from an existing frozenset simply returns the old reference. Otherwise, there doesn't seem to be any significant memory advantage as both frozenset_new and set_new typically end up calling make_new_set with the same arguments.

The reason to use a frozenset rather than a regular set is to reap the benefits of immutability -- e.g. to use an instance because it is hashible or because it is meant to be a constant.

like image 22
mgilson Avatar answered Aug 01 '26 16:08

mgilson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!