building strings from variables

Neil Cerutti horpner at yahoo.com
Fri Oct 6 04:33:03 CEST 2006


On 2006-10-06, MonkeeSage <MonkeeSage at gmail.com> wrote:
> wesley chun wrote:
>> from the performance standpoint, i believe that #4 (list join)
>> from scott is the fastest. #1 (string formatting) is next
>> preferred only because #3 (string concat) is the worst [think
>> "realloc()"].  #2 is useful for when you have users who aren't
>> as comfortable with #1.
>
> I might have done something wrong here, but it looks like the %
> operator would be the fastest (negligibly). And string.Template
> is horribly slow(!).

It is the least mature of all the methods here tested. Perhaps it
will be made faster in the future. I tried your test with a few
variations, and nothing sped it up very much, e.g.; building the
Template object once, outside the test; using keyword args
instead of a dictionary.
 
Template is designed to provide more ammo for regex haters, I
guess.

Template does provide an interface for creating your own slow,
but modified, implementation of Template. ;-)

> import os, sys, string, timeit
>
> hl = [['working_dir', os.getcwd()],
>       ['ssh_cmd'    , 'ssh'],
>       ['some_count' , 5],
>       ['some_param1', 'cheese'],
>       ['some_param2', 'burger']]
>
> hd = dict(hl)
> ht = tuple(map(lambda x: x[1], hl))
> sys.modules['__main__'].__dict__.update(hd)
>
> def make_string_fmt():
>   out = "cd %s ; %s %d %s %s" % ht

Incidentally, changing the fmt test to be more similar to the
Template version doesn't slow it down much.

def make_string_fmt():
  out = "cd %(working_dir)s ; %(ssh_cmd)s %(some_count)d %(some_param1)s"\
        "%(some_param2)s" % hd

-- 
Neil Cerutti



More information about the Python-list mailing list