Advantage of String.format?

G

Guest

Why is String.format better than
just concatenating the string?

is it just the cost of creating a new string? or any thing more?
 
K

Karl Seguin

string.format and string concatenation are two different things. You'd use
string format when you have something like:

string rootPath = "/myApplication/resources/{0}";
string resourcePath = string.Format(rootPath, "Resource.xml");

ie, when you want to format an actual string (either as I've shown or with
additional string formatting)

String concatenation is for adding two string...if you want efficient string
concatenation look at the System.Text.StringBuilder class

Karl
 
B

Brock Allen

Since strings are immutable in .NET, concatenating strings builds another
string. This can lead to inefficiencies if done too much. String.Format uses
the StringBuilder to build the string and the StringBuilder buffers the string
for performance.

-Brock
DevelopMentor
http://staff.develop.com/ballen
 
W

William F. Robertson, Jr.

First, readability is the main reason to use it. Which code is easier to
read?

string s = "<input type=\"";
s += Type;
s += "\" id=\";
s += ID;
s += "\" />";

or

string s = String.Format( @"<input type=""{0}"" id=""{1}"" />", Type, ID );

As far as performance, like Brock said, String.Format using StringBuilder to
build the new string. This is fine when you are concatenating several
strings, but performance on String.Format( "hello{0}, " world" ) will be
better to use string concatenation. StringBuilders aren't free, plus the
StringBuilder still has to parse the string out.

If you are really searching for optimally fast code, you should declare a
StringBuilder and use Append to add the values. But it is a balance between
readability and performance.

System.Text.StringBuilder sb = new StringBuilder( 50 ); //note the initial
size has been set, estimate the total size.
sb.Append( "<input type=\"" );
sb.Append( Type );
sb.Append( "\" id=\" );
sb.Append( ID );
sb.Append( "\" />" );

bill
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top