0

I want to read an input stream with a buffer and append each buffer to a string until the stream is empty.

char[] buffer = new char[32];

while ((bytesRead = streamReader.read(buffer, 0, 32)) != -1)
   message += new String(buffer);

I couldn't find a method of String to append a character array directly and opted for this. Is there a way to know if this is wasting cycles copying the character array to a new string, only to immediately discard it?

This may be premature optimization but it glares at me pretty strongly.

I believe this constructor calls Arrays.copyOf().

Zhro
  • 2,546
  • 2
  • 29
  • 39
  • 3
    Use StringBuilder and its append methods instead of `message += new String(buffer);` – Pshemo Apr 07 '19 at 23:08
  • Possibly related: [Why StringBuilder when there is String?](https://stackoverflow.com/q/5234147) – Pshemo Apr 07 '19 at 23:10
  • 2
    The copying to a String does an extra copy, but is nowhere near as expensive as accumulating into a String instead of a StringBuilder. Also, StringBuilder can append a `char[]` directly, so that's two reasons you should be using StringBuilder. – Louis Wasserman Apr 07 '19 at 23:12
  • You will find over a large file that this is about the worst way to do it, not the best. – user207421 Apr 07 '19 at 23:17

1 Answers1

1

No.

There are more efficient ways. Using a java.util.StringBuilder in your loop is more efficient as it is performing a series of operations. In your loop, += will create another String object each time. For example, if you were to do String d = a + b + c + d... for 1_000_000 Strings, then you'd be making 1_000_000 String objects as waste. Strings are immutable.

Related Link:

String concatenation: concat() vs "+" operator

Off-Site Link but still related https://dzone.com/articles/string-concatenation-performacne-improvement-in-ja

FailingCoder
  • 757
  • 1
  • 8
  • 20