String or tuple and unions

Jeff Epler jepler at
Sun Feb 9 22:00:12 CET 2003

On Sun, Feb 09, 2003 at 08:00:33PM +0000, Grumfish wrote:
> Which is faster to read from, a string or a tuple? All items would be
> 1 unicode character and I would be mostly treating the string as a
> tuple, only looking for items.

You should benchmark this.  When indexing a tuple, a "fresh" object
is never created, just INCREF'd and returned.  When indexing a unicode
string, a fresh 1-character string may be created each time.

> Two more questions, is there a way to find the union of two sets?

If Python had sets (as 2.3a1 does) I'm reasonably certain there would be.

> And
> how fast does the len() function work?

It can work very quickly.  For most (all?) builtin types, len() consists of
returning the length from a field in the C object.  However, __len__ of an
arbitrary object is not necessarily constant-type.

> Would it be worth my while to
> store the length of a large string (or tuple) instad of using len
> several times?

You could benchmark this.  However, it's likely to be a win if it lets you
hoist the function call out of a loop.  A function call is fairly slow, a
load of a "local" variable is fairly fast.


More information about the Python-list mailing list