Commons Lang
  1. Commons Lang
  2. LANG-148

[lang] Performance modifications on StringUtils.replace

    Details

    • Type: Bug Bug
    • Status: Closed
    • Priority: Major Major
    • Resolution: Fixed
    • Affects Version/s: None
    • Fix Version/s: 2.2
    • Component/s: lang.*
    • Labels:
      None
    • Environment:

      Operating System: other
      Platform: Other

      Description

      I dont know how picky you are about performance, but I think it would be nice
      for methods like this not to create new objects (StringBuffers) and copy over,
      if it doesnt need to (e.g. if what you are searching for is not in the "text"
      String). Also, if the text is empty, we can return it right away. And, my
      profiler gets two StringBuffers and an arrayCopy here sometimes since we only
      allocate enough for the original String. I think overall it is better to
      allocate a little more (+20%) for the StringBuffer to reduce this possibility
      and only have 1 StringBuffer to be garbage collected. Feel free to pick and
      choose from any of these ideas.

      public static String replace(String text, String repl, String with, int max) {

      could be written as:

      public static String replace(String text, String repl, String with, int max)
      {
      if (isEmpty(text) || isEmpty(repl) || with == null || max == 0)

      { return text; }
      int start = 0, end = text.indexOf(repl, start);
      if (end == -1) { return text; }

      //add a bit of padding so we reduce the StringBuffer extend capacity
      StringBuffer buf = new StringBuffer(text.length()
      + (text.length() < 20 ? 4 : text.length()/5));
      while (end != -1) {
      buf.append(text.substring(start, end)).append(with);
      start = end + repl.length();

      if (--max == 0)

      { break; }

      end = text.indexOf(repl, start);
      }
      buf.append(text.substring(start));
      return buf.toString();
      }

      I tested it on the test cases in the javadoc and it worked fine.

      Thanks!
      Chris

        Activity

        Hide
        Stephen Colebourne added a comment -

        Code changed, based on code below, but with different algorithm for sizing.
        Please test this algorithm to see if it still helps with your performance issues.

        Show
        Stephen Colebourne added a comment - Code changed, based on code below, but with different algorithm for sizing. Please test this algorithm to see if it still helps with your performance issues.

          People

          • Assignee:
            Unassigned
            Reporter:
            Chris
          • Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

            Dates

            • Created:
              Updated:
              Resolved:

              Development