Home All Groups Group Topic Archive Search About

String conversion from an Object in VB.NET

Author
4 Jan 2005 2:23 PM
Marlon
Which statement gives better performance (where obj can contain any of the
CLR runtime types)


1)  CStr(obj)

or

2) obj.ToString()

Author
4 Jan 2005 3:09 PM
Nick Malik [Microsoft]
They are essentially the same.  CStr(obj) will generate a bit more IL code
than obj.ToString() because it is a call to a function that will turn around
and call ToString anyway.

If you are interested in performance, this article may help:
http://accessvbsql.advisor.com/doc/12798

--
--- Nick Malik [Microsoft]
    MCSD, CFPS, Certified Scrummaster
    http://blogs.msdn.com/nickmalik

Disclaimer: Opinions expressed in this forum are my own, and not
representative of my employer.
   I do not answer questions on behalf of my employer.  I'm just a
programmer helping programmers.
--
Show quoteHide quote
"Marlon" <yardi4life@online.nospam> wrote in message
news:%23xK2tjm8EHA.3416@TK2MSFTNGP09.phx.gbl...
> Which statement gives better performance (where obj can contain any of the
> CLR runtime types)
>
>
> 1)  CStr(obj)
>
> or
>
> 2) obj.ToString()
>
>
Are all your drivers up to date? click for free checkup

Author
5 Jan 2005 3:44 AM
Steven Cheng[MSFT]
Hi Marlon,

From a general view, I always think call obj(or other class's ) ToString
will be better if there is no particular requirement ot use any Convert
class to do the same task. And as for the CStr, this is a visualbasic
compatible expression which is actually translated to the following call at
runtime:

Microsoft.VisualBasic.CompilerServices.StringType.FromObject(Object value)
in microsoft.visualbasic.dll

And the StringType.FromObject will also do a switch list to compare the
object's Typecode and do the convertion. So I think directly use ToString()
method is always the preferred way.
Do you think so?

thanks.

Regards,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)

Bookmark and Share