So, after spending a couple of hours trying to figure out why a particular function was so slow compared to my expectations, I realized my issue dealt with the fact that I forgot about String.concat. I had embedded in my head the past year to always use StringBuilder when possible when concatenating strings. After figuring out why another method was considerably faster, I started to dig into the performance. It is there I realized that String.concat existed and is actually faster in certain cases. Wanting to understand this more, I did a full thorough analysis and comparison. Now, I realize that several others have already undergone this and produced similar results, so you ask, why go through it all again? Well, I wanted to (A) personally verify it myself to learn and understand more (B) dig into the inner depths of the byte code and java code to understand exactly why and (C) to provide more concrete examples and use cases. That being said, continue reading below for my full analysis including my DO lists.
If you do not choose to read any further, at least read the following DO’s:
- DO use the plus operator if all operands are constants
- DO use String.concat if only concatenating 2 strings
- DO use StringBuilder within a for loop when updating values
- DO use StringBuilder if concatenating more than 2 strings
- DO use StringBuilder rather than re-assigning variables multiple times
- DO ensure StringBuilder has proper sizing
