DoNotCastNot necessarily a performance rule?

First, I tried to do something like:

class Class1
{
    public void Do()
    {
    }
}
class Class2
{
    public void Do()
    {
    }
}

...

if (o is Class1)
{
    Class1 c = (Class1)o;
    c.Do();
}
if (o is Class2)
{
    Class2 c = (Class2)o;
    c.Do();
}

but fxcop tells me that: Performance rules. Avoid duplicating drives if possible, as the cost is associated with them. The cache is the result of an "how" statement ...

So I did:

Class1 c1 = o as Class1;
Class2 c2 = o as Class2;
if (c1 != null)
    c1.Do();
if (c2 != null)
    c2.Do();

and no more fxcop errors. But I'm trying to measure if this is really a good performance rule:

static void Main()
    {
        object o = new Class1();
        int cst = 100000000;

        Stopwatch sw1 = new Stopwatch();
        Stopwatch sw2 = new Stopwatch();
        sw1.Start();
        for (int i = 0; i < cst; i++)
        {
            GoodPerf(o);
        }
        sw1.Stop();
        var t1 = sw1.ElapsedMilliseconds;

        sw2.Start();
        for (int i = 0; i < cst; i++)
        {
            BadPerf(o);
        }
        sw2.Stop();
        var t2 = sw2.ElapsedMilliseconds;
        Console.WriteLine(t1);
        Console.WriteLine(t2);
    }

    private static void BadPerf(object o)
    {
        if (o is Class1)
        {
            Class1 c = (Class1)o;
            c.Do();
        }
        if (o is Class2)
        {
            Class2 c = (Class2)o;
            c.Do();
        }
    }

    private static void GoodPerf(object o)
    {
        Class1 c1 = o as Class1;
        Class2 c2 = o as Class2;
        if (c1 != null)
            c1.Do();
        if (c2 != null)
            c2.Do();
    }

And it displays:

2090
1725

2090 should be a good performance ...

So ... I ask if I really need to follow this rule ... Maybe I'm not fixing a good way ...

thanks for your reply

+3
source share
1 answer

FxCop , , . 3 4 , as... FxCop , > 1

, 4.0 VS? , , dynamic , , , , . -2 , , IMO.

, , , .

- , , , , , , .

+1

Source: https://habr.com/ru/post/1729232/


All Articles