String Question

MTSkull

Centurion
Joined
Mar 25, 2003
Messages
151
Location
Boulder, Colorado
Just wondering which (if any) might be better? Since there are at least 4 ways to build a string that I can think of off the top of my head.

Simple String Building
Code:
int val = 2112; 
string myString = "SomeValue " + val.ToString();

string.Format
(what I prefer for readability, especially with bigger string construction)
Code:
int val = 2112; 
string myString = string.Format("SomeValue {0}", val);

or StringBuilder? or string.Concat(string, string...) or some other method I can't think of at the moment. I can think of possibly valid times when I might want to use anyone method over anouther but thought I would let the experts weigh in.

For string arrays StringCollections are heck of Fast, is StringBuilder the speedy equivalent?

Just some random StringBuilding related thoughts.
MTS
 
Ignoring performance issues (as a rule I will unless I know what I am doing is a performance hit) then string.Format wins for me, simply because strings can be shoved in a resx file and localisation (if needed) is made a lot simpler. In fact putting strings in a resx file makes general string maintenance easier regardless of localisation needs.

I would tend to StringCollections over arrays simply for cleaner code, performance wins are a bonus.

When dealing with large strings / many concatenations then StringBuilder is useful, however I tend to find the code I write doesn't involve a lot of large strings so this isn't a class I use a lot.
 
StringBuilder is very fast for building a single large string.

Code:
DateTime start;
            DateTime end;
            TimeSpan diff;

            StringBuilder stringBuild = new StringBuilder();
            String bigString = String.Empty;
            String result = String.Empty;
            start = DateTime.Now;
            for (int i = 0; i < 40000; i++)
                bigString += i.ToString() + " times through.\r\n";
            end = DateTime.Now;
            diff = end.Subtract(start);
            result = "Standard String Concat: " + diff.Milliseconds.ToString() + " milliseconds.\r\n";

            start = DateTime.Now;
            for (int i = 0; i < 40000; i++)
                stringBuild.Append(i.ToString() + " times through.\r\n");

            end = DateTime.Now;
            diff = end.Subtract(start);

            result += "StringBuilder.Append(): " + diff.Milliseconds.ToString() + " milliseconds.\r\n";
            
            MessageBox.Show(result);

I get 800ms for Standard String Contact and 15ms for StringBuilder.Append().

So if you are building a large single string, the StringBuilder is the way to go, for arrays StringCollection seems to work pretty good (not used it alot).

String.Format is good for doing something, but if it is used in a loop performance can become an issue.
 
Back
Top