Last night, I was reading through the MCTS cram guide for Application Developer (and drinking beers) and enjoying a bit of a laugh as I learned ground breaking concepts like “value types” and “creating class” (it’s not all that bad) when I came across this “Strings are immutable in the .NET Framework”.
I’m sure most people reading this (which, of course, assumes anyone is reading this) are either saying, “who cares, even in java strings are immutable, everyone knows this you idiot”, or alternatively asking “what’s an immutable?”. To the first of you I say “fuck off, I skipped most of my compsci classes”, to the rest of you I say ”let me Google that for you…”.
After reading that strings are immutable, I immediately thought of some code I am working on that reads a giant ASCII CSV file about 700k lines long. As part of the process it reads and re-builds a CSV line character by character using nothing but “+=” assignments. I was horrified, as I realized that I was literally creating and assigning millions of string objects unecessarily.
I had done a horrible thing, but I knew how to fix it, use a StringBuilder class instead. Now, my morbid curiosity drove me to fire up my code in dotTrace just to see how horrible. Here are the results for the original method:
1 2 3 4 | |
Results for StringBuilder version:
1 2 3 4 5 | |
Total time went from 143 seconds to 29 seconds. Pretty significant really. So now I know, “strings are immutable stupid!” Thanks MCTS!