obj.ToString(); vs obj + "";

  • Thread starter Thread starter Ray Proffitt
  • Start date Start date
R

Ray Proffitt

Hi.

obj.ToString();

or

obj + "";

Which is more efficient and why?
 
Which is more efficient and why?

By a *very* small margin, the first. The second compiles to
string.Concat(obj) [note that the + "" is optimised away]. This is an
additional method call (which is possibly inlined), but which does an
additional null check (returning "" if obj is null) before calling the
same obj.ToString().

The difference will be stupidly small, and is unlikely to *ever* show
on any performance trace - so go with whichever is simplest to read.
For me, the first wins this. Note that they behave differently for obj
= null, though.

Marc
 
Ray said:
Hi.

obj.ToString();

or

obj + "";

Which is more efficient and why?

The first is slightly more efficient.

Also, it's better from a maintainability perspective. The first code
does exactly what it says, nothing more and nothing less. The second
code describes a nonsense-operation that only has the purpose of causing
an implicit conversion.
 
Ray,

No-one has mentioned the case of obj==null. Makes the two statements quite
different.

Hilton
 
No-one has mentioned the case of obj==null.

Except for: "but which does an additional null check (returning "" if
obj is null) "
and "Note that they behave differently for obj = null, though."

Marc
 
Thanks folks... It's ToString() from now on; always prefered it
anyway.
 
Ray said:
obj.ToString();

or

obj + "";

Which is more efficient and why?

The first, but it does not matter.

What is important is what code clearly expresses
the intent of the code.

And in that aspect the first wins huge.

Arne
 
Convert.ToString(obj). Clear. Safe.

Otherwise, if you good in checking of nulls use your first one. It's much
obvious.

Regards, Alex Meleta
mailto:[email protected]; blog:devkids.blogspot.com
 

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

Back
Top