"?:", "a and b or c" or "iif"

Tim Peters tim_one at email.msn.com
Fri May 28 03:31:49 EDT 1999


[Hrvoje Niksic]
> I had no idea about asserts and -O!

Ignorance of the Reference Manual is no excuse <wink>.

> Currently I'm using `assert' to ensure logical correctness of some
> parts of the code before continuing execution so that the system doesn't
> wind up in an in consistent state, for instance:
> [examples of perfectly reasonable assert stmts]

"assert" is intended for internal consistency checks (not for, e.g.,
validating user input!), which you seem to be doing.  No problem!  Don't
use -O; I rarely do (but do have a handful of modules that use very
expensive asserts heavily, along with very expensive "if __debug__"
blocks; -O yields a huge speedup for those; for most code, -O doesn't buy
enough to bother with).

>> -OO goes on to throw away docstrings.

> Yuck!

Some people with huge docstrings wanted that.

>> ... a peephole optimizer could get rid of the list ops -- but only at
>> the cost of frustrating Michael and Neel's attempts to change what the
>> generated code maps "0" to <0.9 wink>.

> I don't understand this.

Bless you -- nobody should.  Posted an example in a different msg.  Refers
to mucking with the internal structure of code objects, part of which is a
tuple of literals that appeared in the source code.  With much pain and the
use of the undocumented (because unsafe!) "new" module, the internal
structure can be changed.

>> (x and (a,) or (b,))[0]-is-faster-ly y'rs  - tim

> I'm curious -- why?  Is creating and referencing a tuple really faster
> than creating and referencing a list?

Objects in Python never move (id(object)-- which happens to be the object's
memory address --is guaranteed invariant over the life of the object).
Because a list is mutable, it needs to allocate two chunks of storage:  one
for a list header that never moves, and one for a vector of elements that
may need to move as the list grows.  A tuple is immutable, so its storage
need is fixed for all time when it's created, and is allocated (both header
and elements) in one contiguous chunk.  So creating or freeing a list
requires more memory fiddling than creating or freeing a tuple.  Most other
ops are the same (e.g., indexing or finding the length).  In the code above,
creation and destruction cost much more than the indexing, so the tuple
spelling has a significant speed advantage.

OTOH, who cares <0.1 wink>.

it's-a-lame-construction-to-begin-with-ly y'rs  - tim, who invented it






More information about the Python-list mailing list