Re: String.Format vs + operator
- From: "James" <nospam@xxxxxxxxxxxx>
- Date: Mon, 25 Jun 2007 13:30:07 -0500
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]" <MortenWennevik@xxxxxxxxxxx> wrote in message
news:op.tuhpefjedj93y5@xxxxxxxx
On Mon, 25 Jun 2007 20:18:41 +0200, Nicholas Paldino [.NET/C# MVP]
<mvp@xxxxxxxxxxxxxxxxxxxxxxxxxxx> wrote:
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]
.
- Follow-Ups:
- Re: String.Format vs + operator
- From: Göran Andersson
- Re: String.Format vs + operator
- From: Nicholas Paldino [.NET/C# MVP]
- Re: String.Format vs + operator
- References:
- String.Format vs + operator
- From: James
- Re: String.Format vs + operator
- From: Nicholas Paldino [.NET/C# MVP]
- Re: String.Format vs + operator
- From: Morten Wennevik [C# MVP]
- String.Format vs + operator
- Prev by Date: Re: ContainsKey() does not find key
- Next by Date: Re: recursive GetEnumerator()
- Previous by thread: Re: String.Format vs + operator
- Next by thread: Re: String.Format vs + operator
- Index(es):
Relevant Pages
|