Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9204341
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T23:41:25+00:00 2026-06-17T23:41:25+00:00

I used to think that String.replace is faster than String.replaceAll because the latter uses

  • 0

I used to think that String.replace is faster than String.replaceAll because the latter uses Pattern regex and the former does not. But in fact there is no significant difference either in performance or implementation. This is it:

public String replace(CharSequence target, CharSequence replacement) {
    return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
        this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
}

What’s the need to use Pattern here? I wrote a non-regex replace version

static String replace(String s, String target, String replacement) {
    StringBuilder sb = new StringBuilder(s);
    for (int i = 0; (i = sb.indexOf(target, i)) != -1; i += replacement.length()) {
        sb.replace(i, i + target.length(), replacement);
    }
    return sb.toString();
}

and compared performance

    public static void main(String args[]) throws Exception {
        String s1 = "11112233211";
        for (;;) {
            long t0 = System.currentTimeMillis();
            for (int i = 0; i < 1000000; i++) {
//              String s2 = s1.replace("11", "xxx");
                 String s2 = replace(s1, "11", "22");
            }
            System.out.println(System.currentTimeMillis() - t0);
        }
    }

Benchmarks: my version – 400ms; JDK version – 1700ms.

Is my test wrong or is String.replace really inefficient?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T23:41:27+00:00Added an answer on June 17, 2026 at 11:41 pm

    To give you some idea how inefficient String.replace is

    From the source for Java 7 update 11.

    public String replace(CharSequence target, CharSequence replacement) {
        return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
            this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
    }
    

    AFAIK, the use of a Pattern and Matcher.quiteReplacement etc is an attempt to be clear rather than efficient. I suspect it dates back to when many internal libraries were written without performance considerations.

    IMHO Java 7 has seen many internal libraries improve performance, in particular reduce needless object creation. This method is an obvious candidate for improvement.


    You can improve the performance by doing the copy once, instead of trying to insert into an existing StringBuilder.

    static String replace2(String s, String target, String replacement) {
        StringBuilder sb = null;
        int start = 0;
        for (int i; (i = s.indexOf(target, start)) != -1; ) {
            if (sb == null) sb = new StringBuilder();
            sb.append(s, start, i);
            sb.append(replacement);
            start = i + target.length();
        }
        if (sb == null) return s;
        sb.append(s, start, s.length());
        return sb.toString();
    }
    
    public static void main(String... ignored) {
        String s1 = "11112233211";
        for (; ; ) {
            timeReplace(s1);
            timeReplace2(s1);
            timeStringReplaceRefactored(s1);
            timeStringReplace(s1);
        }
    }
    
    private static void timeStringReplace(String s1) {
        long start0 = System.currentTimeMillis();
        for (int i = 0; i < 1000000; i++) {
            String s2 = s1.replace("11", "xxx");
            if (s2.length() <= s1.length()) throw new AssertionError();
        }
        System.out.printf("String.replace %,d ns avg%n", System.currentTimeMillis() - start0);
    }
    
    private static void timeStringReplaceRefactored(String s1) {
        long start0 = System.currentTimeMillis();
        Pattern compile = Pattern.compile("11", Pattern.LITERAL);
        String xxx = Matcher.quoteReplacement("xxx");
        for (int i = 0; i < 1000000; i++) {
            String s2 = compile.matcher(s1).replaceAll(xxx);
            if (s2.length() <= s1.length()) throw new AssertionError();
        }
        System.out.printf("String.replace %,d ns avg (Refactored)%n", System.currentTimeMillis() - start0);
    }
    private static void timeReplace(String s1) {
        long start0 = System.currentTimeMillis();
        for (int i = 0; i < 1000000; i++) {
            String s2 = replace(s1, "11", "xxx");
            if (s2.length() <= s1.length()) throw new AssertionError();
        }
        System.out.printf("Replace %,d ns avg%n", System.currentTimeMillis() - start0);
    }
    
    private static void timeReplace2(String s1) {
        long start0 = System.currentTimeMillis();
        for (int i = 0; i < 1000000; i++) {
            String s2 = replace2(s1, "11", "xxx");
            if (s2.length() <= s1.length()) throw new AssertionError();
        }
        System.out.printf("My replace %,d ns avg%n", System.currentTimeMillis() - start0);
    }
    
    static String replace(String s, String target, String replacement) {
        StringBuilder sb = new StringBuilder(s);
        for (int i = 0; (i = sb.indexOf(target, i)) != -1; i += replacement.length()) {
            sb.replace(i, i + target.length(), replacement);
        }
        return sb.toString();
    }
    

    prints

    Replace 177 ns avg
    My replace 108 ns avg
    String.replace 436 ns avg (Refactored)
    String.replace 598 ns avg
    

    Catching the Pattern and replace text helps a little, but not as much as having a custom routine to do the replace.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I think that I've been used to a fairly liberal policy regarding the PHP
A recent question contains a problem that I many times used to think about
I need a string->string mapping to be used at runtime (think NSDictionary ), except
This example works but I think that the memory leaks. Function used in the
I used to work in JavaScript a lot and one thing that really bothered
Is there a "very bad thing" that can happen &&= and ||= were used
I used to think the db/schema.rb in a Rails project stored the database schema,
I think I may have used a repeater when I should have used something
I think the following code can be used to create manipulators. #include<iostream> ostream &
I think I may misunderstand why the with command is used. But can any

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.