format

Handling strings in .NET can be very expensive, one of the most down to earth recomendations of code profilers often deals with this. In a response on a profiling post (sorry, lost the link..) Frans mentions the good perfomance of the string.format method. AFAIK ( I’m no C guy) in “classical MS languages“ formating strings was mainly done when writing them to output, in the parameters of a print function. In Delphi the ability to format a string has been in the core of the framework ever since the start, the class library houses a global fomat function which looks a lot like the .NET method.


According to my myth format leads to faster and clearer code. Take this:


string.Format(“{0:D} {0:T} : Received {1}.”,DateTime.Now, any);


The parameters passed can be used more than once. Applying a different format on every usage. Of parameter 0, being Now, first the date and than the time is injected into the string.


Not using the format method the code would have looked like this


return DateTime.Now.Date.ToLongDateString() + ” “ + DateTime.Now.ToLongTimeString() + ” : Received “ + any + “.”;


The latter doesn’t look that good but but some profiling learns that it does perform better. There goes my myth..


Peter

This entry was posted in Uncategorized. Bookmark the permalink. Follow any comments here with the RSS feed for this post.