Formatting strings

As a developer, we are constantly working with strings. I mean it, check your code, string operations are all around! And – I can’t help it – each time I see something like this:

var text = year + "/" + month + "/" + day + " " 
+ hour + ":" + minutes + " - "
+ "Completed in " + duration + "seconds.";

I have the irresistible urge to rewrite this to:

var test = string.Format("{0}/{1}/{2} {3}:{4} - Completed in {5} seconds.", 
year, month, day, hour, minutes, duration);

But is it a good idea to do that?

I personally use String.Format almost all of the time for a number of reasons.

First, (re)arranging/maintaining a string is a lot easier than having to (re)arrange/maintain a bunch of variables. Second, you can pass an IFormatProvider, so that you can easily specify formatting options for a specific culture. Third, it’s easier to spot errors. Fourth, consistency.

Now, you probably say: but what about performance?

Indeed, there are alternatives that are ‘faster’. StringBuilder, for one, is probably the most optimized. But really, does this even matter? We’re talking about microseconds here, and micro-optimization is in most cases something you should not think about – remember: premature optimization is the root of all evil:

“The First Rule of Program Optimization: Don’t do it. The Second Rule of Program Optimization (for experts only!): Don’t do it yet.” (Michael A. Jackson)

So unless you are working in a critical high-sensitive real-time system where microseconds are a matter of life and death; or you are messing around with thousands of string operations in a double loop or something; or hundreds of users are executing your string intensive code in parallel – maintainability and readability should be your prime concern.

If eventually performance is bad and should be improved, you can start thinking about measuring and optimizing it; but I hardly think that string concatenation would be your biggest concern in that case.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s