[Tutor] faster substring replacement

Dave Angel davea at ieee.org
Wed Dec 16 11:55:02 CET 2009



R. Alan Monroe wrote:
> <snip>
>
> I'm wondering whether text.replace has to shove oodles of text to the
> right in memory when you replace a shorter word with a longer word.
> Someone else on the list may know.
>
> Alan
>
>
>   
Since a string is immutable, replace() has to copy the string.  So it 
doesn't need to be "shoved to the right" or left.  First copy the part 
before the match.  Then copy the substituted value.  Then copy the part 
after the match.  Still, that's lots of copying.  So it definitely may 
pay off to deal with the text in smaller pieces, either lines or 
"words."  But notice that the replace() method has to be able to handle 
strings that may contain white space, so the optimization needs to be 
done by the developer who knows the constraints of the actual dictionary.


DaveA



More information about the Tutor mailing list