Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

slow string replace #18

Closed
farfromrefug opened this issue Dec 15, 2014 · 1 comment
Closed

slow string replace #18

farfromrefug opened this issue Dec 15, 2014 · 1 comment

Comments

@farfromrefug
Copy link

here you use String.replace with regex.

First question is: is the regex really necessary? I couldn't face a case where it was necessary.
Maybe be you could make it an option? I use your lib for realtime computation and so every little improvement is a big improvement ;)

Now if you decided to go to a simple replace like i did then you would face the problem that String.replace always uses regex and is really slow.

For reference you can use a faster replace like this:

public static String fastReplace(String source, String os, String ns) {
        if (source == null) {
            return null;
        }
        int i = 0;
        if ((i = source.indexOf(os, i)) >= 0) {
            char[] sourceArray = source.toCharArray();
            char[] nsArray = ns.toCharArray();
            int oLength = os.length();
            StringBuilder buf = new StringBuilder(sourceArray.length);
            buf.append(sourceArray, 0, i).append(nsArray);
            i += oLength;
            int j = i;
            // Replace all remaining instances of oldString with newString.
            while ((i = source.indexOf(os, i)) > 0) {
                buf.append(sourceArray, j, i - j).append(nsArray);
                i += oLength;
                j = i;
            }
            buf.append(sourceArray, j, sourceArray.length - j);
            source = buf.toString();
            buf.setLength(0);
        }
        return source;
    }
@uklimaschewski
Copy link
Collaborator

This method may be faster, but it does not work exactly like the regex version.

I tested it and it fails on my TestNested.java JUnit test.
I think, this is because it does not take care the word boundings (The \b in the regex).

If you can come up with a faster, working replacement for the regex, you are welcome to fork and make a pull request with the changes. But make sure that all unit tests pass, before making a pull request.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants