Posts

Showing posts with the label concat

Playing with strings and performance in C#

Image
A few weeks ago, I was solving a problem at HackerRank and after completing a solution that ran  under 100 milliseconds, the program would still timeout during execution. HackerRank limit is usually 1 second, so something was taking more than 900ms. It was the strings! Yes, we know handling strings is costly, but this time there was no way around it.  At the final stage of the problem I had to construct a string over 200k chars long from an array of Boolean values that represented the bits of the number.   Disclaimer : Strings are slow, mainly because they are immutable. Concatenating two strings, creates a third one and possibly 2 for the garbage collector to pickup. Looking through the code I noticed I was simply using " += " instead of StringBuilder.Append method. After using StringBuilder the solution was faster and the submission was approved. It was  fast now, but it got me thinking "how much faster indeed?" which ended with me measuring the perfor