[Python-Dev] Stupid Python Tricks, Volume 38 Number 1

Tim Peters tim.one@home.com
Sat, 20 Jan 2001 16:13:41 -0500


[Tim]
>     huge.join('""')

[Guido]
> Points off for obscurity though!

The Subject line was "Stupid Python Tricks" for a reason <wink>.  Those who
don't know the language inside-out should be tickled by figuring out why it
even *works* (hint for the baffled:  you have to view '""' as a sequence
rather than as an atomic string).

> My favorite for this is:
>
>     '"%s"' % huge
>
> Worth a microbenchmark?

Absolutely!  I get:

     obvious  15.574
     obscure   8.165
     sprintf   8.133

after running:

ITERS = 1000
indices = [0] * ITERS

def obvious(huge):
    for i in indices:  '"' + huge + '"'

def obscure(huge):
    for i in indices:  huge.join('""')

def sprintf(huge):
    for i in indices:  '"%s"' % huge

def runtimes(huge):
    from time import clock
    for f in obvious, obscure, sprintf:
        start = clock()
        f(huge)
        finish = clock()
        print "%12s %7.3f" % (f.__name__, finish - start)

runtimes("x" * 1000000)

under current 2.1a1.  Not a dead-quiet machine, but the difference is too
small to care.  Speed up huge.join attr lookup, and it would probably be
faster <wink>.  Hmm:  if I boost ITERS high enough and cut back the size of
huge, "obscure" eventually becomes *slower* than "obvious", and even if the
"huge.join" lookup is floated out of the loop.  I guess that points to the
relative burden of calling a bound method.  So, in real life, the huge.join
approach may well be the slowest!

>> not-entirely-sure-i'm-channeling-on-this-one-ly y'rs  - tim

> Give up the channeling for a while -- there's too much interference in
> the air from the Microsoft threaded stdio debate still. :-)

What debate?  You need two arguably valid points of view for a debate to
even start <wink>.

gloating-in-victory-vicious-in-defeat-but-simply-unbearable-in-
    ambiguity-ly y'rs  - tim