Casting vs Converting an object toString, when object really is a string

后端 未结 9 2053
终归单人心
终归单人心 2020-11-28 06:13

This isn\'t really an issue, however I am curious. When I save a string in lets say an DataRow, it is cast to Object. When I want to use it, I have to cast it ToString. As f

相关标签:
9条回答
  • 2020-11-28 06:41

    If you know it is a String then by all means cast it to a String. Casting your object is going to be faster than calling a virtual method.

    Edit: Here are the results of some benchmarking:

    ============ Casting vs. virtual method ============
    cast 29.884 1.00
    tos  33.734 1.13
    

    I used Jon Skeet's BenchmarkHelper like this:

    using System;
    using BenchmarkHelper;
    
    class Program
    {
        static void Main()
        {
            Object input = "Foo";
            String output = "Foo";
    
            var results 
               = TestSuite.Create("Casting vs. virtual method", input, output)
                .Add(cast)
                .Add(tos)
                .RunTests()
                .ScaleByBest(ScalingMode.VaryDuration);
    
            results.Display(ResultColumns.NameAndDuration | ResultColumns.Score,
                    results.FindBest());
        }
    
        static String cast(Object o)
        {
            return (String)o;
        }
    
        static String tos(Object o)
        {
            return o.ToString();
        }
    }
    

    So it appears that casting is in fact slightly faster than calling ToString().

    0 讨论(0)
  • 2020-11-28 06:43

    In this case:

    string name = DataRowObject["name"].ToString();
    

    since it is a string, I think that the ToString() method of a string object is simple as:

    return this;
    

    so IMHO there is no performance penalty.

    PS I'm a Java programmer, so this anwser is only a guess.

    0 讨论(0)
  • 2020-11-28 06:49

    The two are intended for different purposes. The ToString method of any object is supposed to return a string representation of that object. Casting is quite different, and the 'as' key word performs a conditional cast, as has been said. The 'as' key word basically says "get me a reference of this type to that object if that object is this type" while ToString says "get me a string representation of that object". The result may be the same in some cases but the two should never be considered interchangeable because, as I said, they exist for different purposes. If your intention is to cast then you should always use a cast, NOT ToString.

    from http://www.codeguru.com/forum/showthread.php?t=443873

    see also http://bytes.com/groups/net-c/225365-tostring-string-cast

    0 讨论(0)
提交回复
热议问题