building strings from variables

MonkeeSage MonkeeSage at
Fri Oct 6 03:42:37 CEST 2006

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(!).

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))

def make_string_fmt():
  out = "cd %s ; %s %d %s %s" % ht
def make_string_cat():
  out = "cd "+working_dir+" ; "+ssh_cmd+" "+str(some_count)+" "+\
        some_param1+" "+some_param2
def make_string_lst():
  out = ' '.join(["cd", working_dir, ";", ssh_cmd,
                 str(some_count), some_param1, some_param2])
def make_string_tmp():
  out = string.Template("cd $working_dir ; $ssh_cmd"
                        "$some_count $some_param1 $some_param2")\

print "String formatting time:"
print timeit.Timer("make_string_fmt()",
                   "from __main__ import make_string_fmt").timeit()
print "String concatination time:"
print timeit.Timer("make_string_cat()",
                   "from __main__ import make_string_cat").timeit()
print "List join time:"
print timeit.Timer("make_string_lst()",
                   "from __main__ import make_string_lst").timeit()
print "Template substitution time:"
print timeit.Timer("make_string_tmp()",
                   "from __main__ import make_string_tmp").timeit()



String formatting time:
String concatination time:
List join time:
Template substitution time:


More information about the Python-list mailing list