1

I am not sure if this is the right place to ask this.

I was looking into different ways to concat a string in java.

Found out that concatenating with + is inefficient when done in loops as it creates new objects every time.

Where is the code that does the concatenation when + is used written? I was able to look at implementations of StringBuilder, concat() and StringBuffer but cannot find the implementation for +.

Apologies if this is the wrong forum.

leoOrion
  • 1,833
  • 2
  • 26
  • 52
  • Sounds like you mostly know the right answer already. `+` is slower because it allocates new strings for each operation. StringBuilder and StringBuffer use an array with extra space to save them from creating new space in memory for each 'concat' operation. Is it the specific low-level detail of how `+` operates you're interested in? – Cuga Jul 24 '19 at 14:47
  • @Cuga yes. I was reading this blog http://www.pellegrino.link/2015/08/22/string-concatenation-with-java-8.html. In the `Understanding the issue` section, it says that new array instances are created and existing data is copied into them. Wanted to see how that was achieved. – leoOrion Jul 24 '19 at 15:08
  • It is probably implementation dependent. But all you need to do is use a `class viewer` to look at the `byte code`. Oracle's java uses 'Stringbuilder'. – WJS Jul 24 '19 at 16:52

0 Answers0