Can you make this faster?

William Park opengeometry at yahoo.ca
Mon Jun 28 05:21:46 CEST 2004


William Park <opengeometry at yahoo.ca> wrote:
> Kamilche <klachemin at home.com> wrote:
> > def fmtstring(args):
> >     delim = '\0'
> >     fmt = []
> >     fmt.append('<')
> >     for arg in args:
> >         t = type(arg)
> >         if t == types.StringType:
> >             l = len(arg)
> >             fmt.append(str(l) + 's')
> >         elif t == types.IntType:
> >             fmt.append('i')
> >         elif t == types.LongType:
> >             fmt.append('q')
> >         elif t == types.BooleanType:
> >             fmt.append('c')
> >         elif t == types.FloatType:
> >             fmt.append('d')
> >         else:
> >             raise Exception("Can't pack argument of type %s!" % t)
> >     s = ''.join(fmt)
> >     s = s + '\0'
> >     return s
> 
> String concatenation ('+') is main culprit.  Avoid it. 
> 
>     Before              After
>     ------              -----
>     str(l) + 's'        fmt.append (str(l))
>                         fmt.append ('s')
>     
>     s = ''.join(fmt)    fmt.append ('\0')
>     s = s + '\0'        ''.join(fmt)

Also, change 'fmt.append' and 'types.*' with a version without '.', ie.
    fmtappend = fmt.append
    types_s = types.StringType
    stringjoin = string.join

-- 
William Park, Open Geometry Consulting, <opengeometry at yahoo.ca>
Q: What do you use to remove bugs on Windows?  A: Windex.



More information about the Python-list mailing list