Friday, November 14, 2008

Improve the performance of you string

As we know,Python's string object is immutable,that means you can't change it in-place.Each time when you operate on a string it'll generate a new string object.Sometime it's not good,especially when your string is big.A method to solving this performance issue is use List object.first we convert a string to a list,now it's mutable ,secondly we manipulate this list,if it's done we convert to string.following is an example:
#Python code
#firstly, we define a new string,it's a poem ,a big string
bigstring=""""
Today I saw a butterfly,
as it floated in the air;
Its wings were spread in splendor,
Unaware that I was there.
""""
#secondly, we convert it to a list
biglist=bigstring.split(' ')
biglist[1]='you'
biglist[3]="one"
#convert it back
bigstring=''.join(biglist)
bigstring

Because list is mutable,each time we operate on it,no new object generated.So we have high performance.

No comments: