In my current project there are two types of data holder objects defined: business objects, used by the server side of the application and value objects (aka data transfer objects) which are very very very (etc.) similar to business objects in terms of properties. These types of value objects are used to pass data to the client. Nothing new so far, this actually happens in pretty many projects.
I often hear people claim that using string concatenations inside loops comes with a huge penalty given the performance. Usually no one knows exactly how much this penalty is; so I decided to measure it.
For this I created a very simple application, that keeps adding the string representation of the current iteration to the end of a String/StringBuilder, with the number of words increasing incrementally from 1 to a million. Actually, I am biased toward Strings, because I think they create cleaner and more readable code than StringBuilders. Having said that, let’s see how my tests performed. Here are the results:
String concat for 1 substrings: 0 millisecs.
StringBuilder concat for 1 substrings: 0 millisecs.
String concat for 10 substrings: 0 millisecs.
StringBuilder concat for 10 substrings: 0 millisecs.
String concat for 100 substrings: 1 millisecs.
StringBuilder concat for 100 substrings: 0 millisecs.
String concat for 1,000 substrings: 3 millisecs.
StringBuilder concat for 1,000 substrings: 0 millisecs.
String concat for 10,000 substrings: 179 millisecs.
StringBuilder concat for 10,000 substrings: 1 millisecs.
String concat for 100,000 substrings: 18635 millisecs.
StringBuilder concat for 100,000 substrings: 2 millisecs.
String concat for 1,000,000 substrings: 2919877 millisecs. //Well, this is more than 48 minutes… Sweet.
StringBuilder concat for 1,000,000 substrings: 24 millisecs.
In conclusion, in case of a loop with a thousand iterations makes no relevant difference with regard to runtime; above that threshold, however, it is not worth using Strings. I can hardly imagine such a huge String concat loop, though in production environments.
I have to say that the difference in the last case surprised me a lot; 48 minutes compared to 24 milliseconds, this is shocking (of course this is not a realistic example, I only included it for fun. Waiting for the app to terminate, however, was not funny at all).
That’s it, mystery solved.