473,217 Members | 1,979 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,217 software developers and data experts.

String.Format vs + operator

Which is better, which is faster, which is easier etc... ?????

String.Format ( "yadda {0} yadda {1}", x, y )

"yadda" + x.ToString() + " yadda" + y.tostring();
My code has a mish mash of both and I am wondewring if I should standardize
or not ??
Thnanks,

JIM
Jun 25 '07 #1
15 2572
On Jun 25, 11:10 am, "James" <nos...@hypercon.netwrote:
Which is better, which is faster, which is easier etc... ?????

String.Format ( "yadda {0} yadda {1}", x, y )

"yadda" + x.ToString() + " yadda" + y.tostring();

My code has a mish mash of both and I am wondewring if I should standardize
or not ??
In addition to what other posters have mentioned, keep in mind that if
you ever want to internationalize your code, the "+" operator way is a
non-starter.

Jun 25 '07 #2
On Mon, 25 Jun 2007 20:18:41 +0200, Nicholas Paldino [.NET/C# MVP] <mv*@spam.guard.caspershouse.comwrote:
James,

Using the + operator will be faster, as it will just pre-allocate the
string and copy the various elements together. With Format, the format
string is parsed, and that is going to require some overhead.

However, I do think that you should carefully consider the overhead
versus the readability/maintainability of the code, as I think that the call
to Format is MUCH much better in this arena.

Of course, if you have a good number of these operations being
performed, then you could gain some performance by moving to the concat
operator (+).

In some cases I agree, but in many cases readability can be much improved by not calling ToString(), in which case the OP's example narrows downto

string s = "yadda " + x + " yadda " + y;

which I would argue is more readable (syntax coloring will make it even more readable) than

string s = string.Format("yadda {0} yadda {1}", x, y);
PS! If any of the parts of a string concatenation contains a string literal, ToString() will automatically be called on other parts as well.

--
Happy coding!
Morten Wennevik [C# MVP]
Jun 25 '07 #3
Ok, thanks,

JIM
"Tom Spink" <ts****@gmail.comwrote in message
news:uj**************@TK2MSFTNGP03.phx.gbl...
James wrote:
>Which is better, which is faster, which is easier etc... ?????

String.Format ( "yadda {0} yadda {1}", x, y )

"yadda" + x.ToString() + " yadda" + y.tostring();
My code has a mish mash of both and I am wondewring if I should
standardize or not ??
Thnanks,

JIM

Hi Jim,

IIRC, concatenation is faster, but you should choose based on whether you
actually need to gain speed when concatenating strings (i.e. is your
application performance critical) and then decided whether you should
sacrifice code readability for a slight performance improvement.

--
Tom Spink
University of Edinburgh

Jun 25 '07 #4
Excellent, thanks

JIM
"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.comwrote in
message news:ef**************@TK2MSFTNGP04.phx.gbl...
James,

Using the + operator will be faster, as it will just pre-allocate the
string and copy the various elements together. With Format, the format
string is parsed, and that is going to require some overhead.

However, I do think that you should carefully consider the overhead
versus the readability/maintainability of the code, as I think that the
call to Format is MUCH much better in this arena.

Of course, if you have a good number of these operations being
performed, then you could gain some performance by moving to the concat
operator (+).
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"James" <no****@hypercon.netwrote in message
news:OY**************@TK2MSFTNGP06.phx.gbl...
>Which is better, which is faster, which is easier etc... ?????

String.Format ( "yadda {0} yadda {1}", x, y )

"yadda" + x.ToString() + " yadda" + y.tostring();
My code has a mish mash of both and I am wondewring if I should
standardize or not ??
Thnanks,

JIM


Jun 25 '07 #5
Readability, versus perfrmance.

The funny thing here is that, for me, the + operator is easier to read than
and brackets {0} etc... So, for me it looks like I get readability and
performance with the + operator.

Is that jus me or do other also rad the+ easier than the .Format .... ??
thanks,

JIM

"James" <no****@hypercon.netwrote in message
news:OY**************@TK2MSFTNGP06.phx.gbl...
Which is better, which is faster, which is easier etc... ?????

String.Format ( "yadda {0} yadda {1}", x, y )

"yadda" + x.ToString() + " yadda" + y.tostring();
My code has a mish mash of both and I am wondewring if I should
standardize or not ??
Thnanks,

JIM

Jun 25 '07 #6
YES !!! Thank you, this is exactly what I have always thought but wanted to
confirm with other developers. Glad to hear I am not alone on this. Syntax
highligting rocks for this too.

JIM

"Morten Wennevik [C# MVP]" <Mo************@hotmail.comwrote in message
news:op.tuhpefjedj93y5@stone...
On Mon, 25 Jun 2007 20:18:41 +0200, Nicholas Paldino [.NET/C# MVP]
<mv*@spam.guard.caspershouse.comwrote:
James,

Using the + operator will be faster, as it will just pre-allocate the
string and copy the various elements together. With Format, the format
string is parsed, and that is going to require some overhead.

However, I do think that you should carefully consider the overhead
versus the readability/maintainability of the code, as I think that the
call
to Format is MUCH much better in this arena.

Of course, if you have a good number of these operations being
performed, then you could gain some performance by moving to the concat
operator (+).

In some cases I agree, but in many cases readability can be much improved by
not calling ToString(), in which case the OP's example narrows down to

string s = "yadda " + x + " yadda " + y;

which I would argue is more readable (syntax coloring will make it even more
readable) than

string s = string.Format("yadda {0} yadda {1}", x, y);
PS! If any of the parts of a string concatenation contains a string literal,
ToString() will automatically be called on other parts as well.

--
Happy coding!
Morten Wennevik [C# MVP]
Jun 25 '07 #7
James,

Curious, if your choice is strictly about readability, then what does it
matter what other developers think is readable or not readable? What
matters is the developers who are maintaining the codebase that you all are
working on. It's a subjective matter at that point.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com
"James" <no****@hypercon.netwrote in message
news:%2****************@TK2MSFTNGP06.phx.gbl...
YES !!! Thank you, this is exactly what I have always thought but wanted
to confirm with other developers. Glad to hear I am not alone on this.
Syntax highligting rocks for this too.

JIM

"Morten Wennevik [C# MVP]" <Mo************@hotmail.comwrote in message
news:op.tuhpefjedj93y5@stone...
On Mon, 25 Jun 2007 20:18:41 +0200, Nicholas Paldino [.NET/C# MVP]
<mv*@spam.guard.caspershouse.comwrote:
>James,

Using the + operator will be faster, as it will just pre-allocate the
string and copy the various elements together. With Format, the format
string is parsed, and that is going to require some overhead.

However, I do think that you should carefully consider the overhead
versus the readability/maintainability of the code, as I think that the
call
to Format is MUCH much better in this arena.

Of course, if you have a good number of these operations being
performed, then you could gain some performance by moving to the concat
operator (+).


In some cases I agree, but in many cases readability can be much improved
by not calling ToString(), in which case the OP's example narrows down to

string s = "yadda " + x + " yadda " + y;

which I would argue is more readable (syntax coloring will make it even
more readable) than

string s = string.Format("yadda {0} yadda {1}", x, y);
PS! If any of the parts of a string concatenation contains a string
literal, ToString() will automatically be called on other parts as well.

--
Happy coding!
Morten Wennevik [C# MVP]

Jun 25 '07 #8
James wrote:
Readability, versus perfrmance.

The funny thing here is that, for me, the + operator is easier to read
than and brackets {0} etc... So, for me it looks like I get readability
and performance with the + operator.

Is that jus me or do other also rad the+ easier than the .Format .... ??
thanks,

JIM

"James" <no****@hypercon.netwrote in message
news:OY**************@TK2MSFTNGP06.phx.gbl...
>Which is better, which is faster, which is easier etc... ?????

String.Format ( "yadda {0} yadda {1}", x, y )

"yadda" + x.ToString() + " yadda" + y.tostring();
My code has a mish mash of both and I am wondewring if I should
standardize or not ??
Thnanks,

JIM
Hi Jim,

It does boil down to personal preference, but it also depends on the context
of your concatenation. You may have a complex string being built (such as
an SQL query, or some other stringified command that takes parameters
enclosed in quotes, brackets and whatnot - or multiple instances of the
same string), in which case I'd argue string.Format is more readable since:

1. It detaches the template of the string your creating from the parameters,
allowing for multiple uses of the same variable without duplicating
concatenation.

2. It provides a level of readability like that of a function call that
takes parameters, i.e. creating an SQL query.

--
Tom Spink
University of Edinburgh
Jun 25 '07 #9
Nicholas, what matters is that what is readble for ME also happens to be
the fastest, so for ME, I get the baset of both worlds, whereas for OTHERS,
they get what they believe is more readable, but they lose the speed factor.
So, my way appears to be the best way, that is if you apply logic to my
argument

JIM
"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.comwrote in
message news:uO**************@TK2MSFTNGP05.phx.gbl...
James,

Curious, if your choice is strictly about readability, then what does
it matter what other developers think is readable or not readable? What
matters is the developers who are maintaining the codebase that you all
are working on. It's a subjective matter at that point.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com
"James" <no****@hypercon.netwrote in message
news:%2****************@TK2MSFTNGP06.phx.gbl...
>YES !!! Thank you, this is exactly what I have always thought but wanted
to confirm with other developers. Glad to hear I am not alone on this.
Syntax highligting rocks for this too.

JIM

"Morten Wennevik [C# MVP]" <Mo************@hotmail.comwrote in message
news:op.tuhpefjedj93y5@stone...
On Mon, 25 Jun 2007 20:18:41 +0200, Nicholas Paldino [.NET/C# MVP]
<mv*@spam.guard.caspershouse.comwrote:
>>James,

Using the + operator will be faster, as it will just pre-allocate
the
string and copy the various elements together. With Format, the format
string is parsed, and that is going to require some overhead.

However, I do think that you should carefully consider the overhead
versus the readability/maintainability of the code, as I think that the
call
to Format is MUCH much better in this arena.

Of course, if you have a good number of these operations being
performed, then you could gain some performance by moving to the concat
operator (+).


In some cases I agree, but in many cases readability can be much improved
by not calling ToString(), in which case the OP's example narrows down to

string s = "yadda " + x + " yadda " + y;

which I would argue is more readable (syntax coloring will make it even
more readable) than

string s = string.Format("yadda {0} yadda {1}", x, y);
PS! If any of the parts of a string concatenation contains a string
literal, ToString() will automatically be called on other parts as well.

--
Happy coding!
Morten Wennevik [C# MVP]


Jun 25 '07 #10
The point I was trying to make is that you shouldn't be seeking
justification on subjective matters from those who's opinion on said
subjective matters doesn't matter.

In this case, the performance issue is not subjective, it is objective.

However, which is more readable, is subjective. If you are the only
person writing/maintaining the code, and that's what works for you, then
great, but if you are working in a team and others have to work with the
code that you write, then it is a team decision (or the team lead, or
whatever) as to what is more readable, not us.

--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"James" <no****@hypercon.netwrote in message
news:uR*************@TK2MSFTNGP04.phx.gbl...
Nicholas, what matters is that what is readble for ME also happens to be
the fastest, so for ME, I get the baset of both worlds, whereas for
OTHERS, they get what they believe is more readable, but they lose the
speed factor. So, my way appears to be the best way, that is if you apply
logic to my argument

JIM
"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.comwrote
in message news:uO**************@TK2MSFTNGP05.phx.gbl...
>James,

Curious, if your choice is strictly about readability, then what does
it matter what other developers think is readable or not readable? What
matters is the developers who are maintaining the codebase that you all
are working on. It's a subjective matter at that point.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com
"James" <no****@hypercon.netwrote in message
news:%2****************@TK2MSFTNGP06.phx.gbl...
>>YES !!! Thank you, this is exactly what I have always thought but wanted
to confirm with other developers. Glad to hear I am not alone on this.
Syntax highligting rocks for this too.

JIM

"Morten Wennevik [C# MVP]" <Mo************@hotmail.comwrote in message
news:op.tuhpefjedj93y5@stone...
On Mon, 25 Jun 2007 20:18:41 +0200, Nicholas Paldino [.NET/C# MVP]
<mv*@spam.guard.caspershouse.comwrote:

James,

Using the + operator will be faster, as it will just pre-allocate
the
string and copy the various elements together. With Format, the format
string is parsed, and that is going to require some overhead.

However, I do think that you should carefully consider the overhead
versus the readability/maintainability of the code, as I think that the
call
to Format is MUCH much better in this arena.

Of course, if you have a good number of these operations being
performed, then you could gain some performance by moving to the concat
operator (+).

In some cases I agree, but in many cases readability can be much
improved by not calling ToString(), in which case the OP's example
narrows down to

string s = "yadda " + x + " yadda " + y;

which I would argue is more readable (syntax coloring will make it even
more readable) than

string s = string.Format("yadda {0} yadda {1}", x, y);
PS! If any of the parts of a string concatenation contains a string
literal, ToString() will automatically be called on other parts as well.

--
Happy coding!
Morten Wennevik [C# MVP]



Jun 25 '07 #11
On Mon, 25 Jun 2007 11:52:49 -0700, James <no****@hypercon.netwrote:
Nicholas, what matters is that what is readble for ME also happens to be
the fastest, so for ME, I get the baset of both worlds, whereas for
OTHERS,
they get what they believe is more readable, but they lose the speed
factor.
So, my way appears to be the best way, that is if you apply logic to my
argument
It is only the "best way" for you. That's what makes it subjective. Only
in very narrow, specific situations can performance be considered a high
enough priority to completely override readability.

Your paragraph above appears to be saying that others' idea of "readable"
is wrong because it leads to (very slightly) reduced performance. IMHO,
that's a false conclusion, since readability and performance are two
separate things and furthermore, readability is subjective while
performance is not.

As far as whether using concatenation is more readable than using string
formatting goes, that's completely in the eye of the beholder. But as
others have pointed out, there are good arguments in favor of using string
formatting. Bruce pointed out that anything that requires localization or
similar need to provide alternative formatting strings is going to be much
harder with concatenation, and I also agree that there are many cases
where being able to see the entire base string is more readable than
having to look at code that concatenates several string literals with data
interspersed.

You are welcome to your opinion that concatenation is more readable, but
don't think that it is "logical" to conclude that everyone else should
agree that it's more readable just because concatenation also happens to
perform better (however slightly).

Pete
Jun 25 '07 #12
James wrote:
In some cases I agree, but in many cases readability can be much improved by
not calling ToString(), in which case the OP's example narrows down to

string s = "yadda " + x + " yadda " + y;

which I would argue is more readable (syntax coloring will make it even more
readable) than
Yes, it's more readable, but also slower. If not all items are strings,
all items will instead be cast to object. Items that are value types
will therefore be boxed.

The generated code is actually:

string s = String.Concat((object)"yadda ", (object)x, (object)" yadda ",
(object)y);

The Concat method will then call the ToString method for all the
objects, even those that are already strings.
string s = string.Format("yadda {0} yadda {1}", x, y);
PS! If any of the parts of a string concatenation contains a string literal,
ToString() will automatically be called on other parts as well.
No, that is not correct. If any of the items is not a string, all items
are instead cast to object.

--
Göran Andersson
_____
http://www.guffa.com
Jun 26 '07 #13
On Jun 26, 9:43 am, Göran Andersson <g...@guffa.comwrote:
In some cases I agree, but in many cases readability can be much improved by
not calling ToString(), in which case the OP's example narrows down to
string s = "yadda " + x + " yadda " + y;
which I would argue is more readable (syntax coloring will make it evenmore
readable) than

Yes, it's more readable, but also slower.
Nope, I don't believe so.
If not all items are strings, all items will instead be cast
to object. Items that are value types will therefore be boxed.
How would you expect value types to be passed to String.Format without
boxing taking place?
The generated code is actually:

string s = String.Concat((object)"yadda ", (object)x, (object)" yadda ",
(object)y);

The Concat method will then call the ToString method for all the
objects, even those that are already strings.
Just the same as string.Format does...

Now, as for your claim that calling Format is faster, here's a
microbenchmark. I wouldn't be surprised to see results change
depending on the exact format etc, but it does show (at least on my
box) that string.Concat is faster in *some* situations:

using System;
using System.Diagnostics;

class Test
{
const int Iterations = 10000000;

static void Main()
{
int x = 5;

Stopwatch timer = Stopwatch.StartNew();
for (int i=0; i < Iterations; i++)
{
string y = "hello" + x + "there";
}
long ms = timer.ElapsedMilliseconds;
Console.WriteLine ("Concat took: {0}ms", ms);
GC.Collect();
timer = Stopwatch.StartNew();
for (int i=0; i < Iterations; i++)
{
string y = string.Format("hello {0} there", x);
}
ms = timer.ElapsedMilliseconds;
Console.WriteLine ("Format took: {0}ms", ms);
}
}

Results:

Concat took: 2528ms
Format took: 5536ms

Jon

Jun 26 '07 #14
On Jun 26, 10:02 am, "Jon Skeet [C# MVP]" <s...@pobox.comwrote:
which I would argue is more readable (syntax coloring will make it even more
readable) than
Yes, it's more readable, but also slower.

Nope, I don't believe so.
<snip>

Ah. Just reread your post. I assume now that you were *actually*
saying that

string y = "a" + b + "c";
is slower than
string y = "a" + b.ToString() + "c";

in which case I agree. Oops.

Jon

Jun 26 '07 #15
Jon Skeet [C# MVP] wrote:
On Jun 26, 10:02 am, "Jon Skeet [C# MVP]" <s...@pobox.comwrote:
>>>which I would argue is more readable (syntax coloring will make it even more
readable) than
Yes, it's more readable, but also slower.
Nope, I don't believe so.

<snip>

Ah. Just reread your post. I assume now that you were *actually*
saying that

string y = "a" + b + "c";
is slower than
string y = "a" + b.ToString() + "c";

in which case I agree. Oops.

Jon
Yes, that's what I meant. Sorry for not being specific about what I was
comparing against. :)

--
Göran Andersson
_____
http://www.guffa.com
Jun 26 '07 #16

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Jonas Galvez | last post by:
Is it true that joining the string elements of a list is faster than concatenating them via the '+' operator? "".join() vs 'a'+'b'+'c' If so, can anyone explain why?
5
by: Thomas Philips | last post by:
Consider the following simple dictionary e={1:'one', 2: 'two'} e >>>'one' However, If I attempt to print e using a formatted string print " %(1)s" %e, I get a KeyError: '1'
11
by: Frank Neuhaus | last post by:
Hey Iam occaisonally using something like char buffer; sprinf(buffer,"Hello test %d %s",someint,somestring); Is there any _convenient_ and buffer overflow secure equivalent for that using...
16
by: Don Starr | last post by:
When applied to a string literal, is the sizeof operator supposed to return the size of the string (including nul), or the size of a pointer? For example, assuming a char is 1 byte and a char *...
7
by: Brian Mitchell | last post by:
Is there an easy way to pull a date/time stamp from a string? The DateTime stamp is located in different parts of each string and the DateTime stamp could be in different formats (mm/dd/yy or...
15
by: Kapil Jain | last post by:
Dear All, What i need to achieve is : I am generating dynamic text boxes thru dhtml coding, i need onChange event of oragnistation text box i.e dynamically generated on click of "More" button in...
16
by: Mark A. Sam | last post by:
Hello, I am having a problem with imputting into a string variable: Dim strSQL As String = "INSERT INTO tblContactForm1 (txtName, txtCompany, txtPhone, txtEmail, txtComment, chkGrower,...
9
by: Terry Olsen | last post by:
I send out a daily email to technicians regarding nightly backup logs. I use the following code to generate the body of the email: tmpBody += vbCrLf tmpBody += "----- " & SupTechs.Item(j) & " ("...
18
by: subramanian100in | last post by:
Consider a class that has vector< pair<int, string>* c; as member data object. I need to use operator>to store values into this container object and operator<< to print the contents of the...
1
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
0
by: veera ravala | last post by:
ServiceNow is a powerful cloud-based platform that offers a wide range of services to help organizations manage their workflows, operations, and IT services more efficiently. At its core, ServiceNow...
0
by: VivesProcSPL | last post by:
Obviously, one of the original purposes of SQL is to make data query processing easy. The language uses many English-like terms and syntax in an effort to make it easy to learn, particularly for...
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 3 Jan 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). For other local times, please check World Time Buddy In...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.