Thursday, May 26, 2011

String + String = Problems

This is just a quick note to everyone not knowing it.

If for whatever reason you do have in your code something that concatenates strings using the + (plus) operator and it's going on in any form of loop or other that means executing this part regularly you might want to rethink what you've become over the years.

Man I never thought I'll see this thing again but I did! One of the developers was (again) producing a CVS line using a + b + c + d + shit load of other stuff. I mean come on! There have been books written about it already! :)

So if you're a Java developer choose one of either String.format, StringBuilder or StringBuffer classes to do the concatenation for you. If you're a .NET use either String.Format or StringBuilder to do it efficiently.

If you're a lucky Groovy developer your string concatenation will not be efficient anyway so you're free to use string interpolation - you can't get any worse than that :) At least it's damn good readable!

Sure thing is that depending on which platform you use concatenating might be more efficient if you use (for example in C#) the String.Concat method. But overall if you're concatenating a large number of strings (say in a loop or so) use the builder things at your disposal - they're a safe bet.

No comments: