Uploaded image for project: 'Commons Lang'
  1. Commons Lang
  2. LANG-993

Add zero copy write method to StrBuilder

    XMLWordPrintableJSON

Details

    • Improvement
    • Status: Closed
    • Major
    • Resolution: Fixed
    • 3.3.1
    • 3.4
    • lang.text.*
    • None

    Description

      Currently I have the following usecase:

      StrBuilder builder = new StrBuilder();
      // add lots of stuff to builder
      // in multiple invocations in several classes
      // writer cannot be used directly
      builder.append(...);
      
      Writer writer = ....;
      CharStreams.copy(builder.asReader(), writer);
      

      CharStreams is a class from Guava lib that copies data between reader and writer using temporary buffer.
      There is a problem with such approach - two additional copies are performed:
      1) data is copied from the StrBuilder in chunks into temporary buffer (CharBuffer)
      2) Writer.append(CharSequence) is called that is usually implemented as write(CharSequence.toString()) - i.e. it makes another copy of data and allocates an additional String object.

      I want to avoid those copies by writing the internal buffer of the StrBuilder directly to the writer. Also it is potentially more efficient because it performs one I/O call instead of many.

      So I propose to add the following methods:

          public void writeTo(Writer writer) throws IOException {
              writer.write(buffer, 0, size);
          }
      
          public void writeTo(StringBuilder builder) {
              builder.append(buffer, 0, size);
          }
      
          public void writeTo(StringBuffer buffer) {
              buffer.append(this.buffer, 0, size);
          }
      

      If there is interest I will provide patch (with JavaDocs and tests).

      Attachments

        1. LANG-993.patch
          4 kB
          Mikhail Mazursky
        2. LANG-993-994.patch
          7 kB
          Mikhail Mazursky

        Issue Links

          Activity

            People

              britter Benedikt Ritter
              ash2k Mikhail Mazursky
              Votes:
              0 Vote for this issue
              Watchers:
              3 Start watching this issue

              Dates

                Created:
                Updated:
                Resolved: