[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [cp-patches] Patch: 2 API methods implemented in java.lang.String
From: |
Anthony Balkissoon |
Subject: |
Re: [cp-patches] Patch: 2 API methods implemented in java.lang.String |
Date: |
Mon, 07 Nov 2005 16:02:27 -0500 |
On Mon, 2005-11-07 at 12:39 -0700, Tom Tromey wrote:
> >>>>> "Tony" == Anthony Balkissoon <address@hidden> writes:
> Tony> + public String replace (CharSequence target, CharSequence replacement)
> Tony> + {
> Tony> + String result = this;
> Tony> + int pos = result.indexOf(target.toString());
> Tony> + while (pos != -1)
> Tony> + {
> Tony> + result = result.substring(0, pos) + replacement.toString()
> Tony> + + result.substring(pos + target.length(),
> result.length());
> Tony> + pos = result.indexOf(target.toString());
> Tony> + }
> Tony> + return result;
> Tony> + }
> Tony> }
>
> This is inefficient. For one thing, target is converted to a String
> twice. For another, it creates a lot of garbage if there is more than
> one match.
>
> It is also incorrect, consider what happens if the replacement string
> contains the target string.
Thanks Tom. I fixed this now, it uses a StringBuffer for better
performance and also only checks for occurrences of the target string
that occur after the replacement insertion. Also doesn't re-initialize
the start part of the String each time which was just wasteful.
2005-11-07 Anthony Balkissoon <address@hidden>
* java/lang/String.java:
(replace): Use a StringBuffer instead of String. Only search for new
occurrences of the target that occur AFTER the text just inserted, so
if the replacement string contains the target string we won't go into
an infinite loop. Use local variables instead of repeated calls to
length() and toString().
StringReplaceFix.diff
Description: Text Data