Design patterns in the real world: Flyweight

Quite some software engineers think that design patterns are some overly complicated, mythical, abstract things that bring no practical value to software development. This is unfortunate. In order to prove they are indeed something real, in this (and some upcoming) post(s) we are going to take a look on a few examples on how real software products implement some of the GoF design patterns. The first one to be examined is Flyweight.

Continue reading “Design patterns in the real world: Flyweight”

Advertisements

String concatenation VS StringBuilder append

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.