Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8058779

Faster implementation of String.replace(CharSequence, CharSequence)

    XMLWordPrintable

Details

    • b68
    • x86_64
    • windows_7

    Backports

      Description

        A DESCRIPTION OF THE REQUEST :
        The implementation of java.lang.String.replace(CharSequence, CharSequence) uses regex as the implementation which is not as ideal an implementation as some alternatives.

        Here's the current implementation from Java 8u20 (which has been in place since the method was added in Java 5):
            public String replace(CharSequence target, CharSequence replacement) {
                return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
                        this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
            }

        JUSTIFICATION :
        The current implementation uses regular expressions, which needs to initialize the regex engine and load many regex classes that are pretty heavy-weight. This reasoning was also applied in JDK-6840246 where the implementation of String.split was improved.

        The regular expressions also take a lot longer than to run than alternative implementations, such as that used by Apache Commons Lang: http://grepcode.com/file/repo1.maven.org/maven2/org.apache.commons/commons-lang3/3.3.2/org/apache/commons/lang3/StringUtils.java#StringUtils.replace%28java.lang.String%2Cjava.lang.String%2Cjava.lang.String%29

        There are many write ups on many sites discussing how Java's String.replace is slow and that for decent performance an alternative has to be used:
        https://stackoverflow.com/questions/16228992/commons-lang-stringutils-replace-performance-vs-string-replace
        https://www.cqse.eu/en/blog/string-replace-performance/
        http://www.myhowto.org/under-the-hood/32-hidden-costs-of-using-java-string-methods/

         It would be really great to have the best implementation be in the JRE so everyone benefits and no one has to encounter this performance issue and work around it using 3rd party libraries.


        Attachments

          Issue Links

            Activity

              People

                igerasim Ivan Gerasimov
                webbuggrp Webbug Group
                Votes:
                0 Vote for this issue
                Watchers:
                4 Start watching this issue

                Dates

                  Created:
                  Updated:
                  Resolved: