How expensive are dots in .NET?

.net, c#, pointers, vb.net

Solution

This is an apples and oranges comparison.

System.Runtime.InteropServices.Marshal.WriteInt32(Abort, 1)

is equivalent to this in C++:

Foo::Bar::Baz::Func(a, b);

In other words, namespaces fold up into zero cost by the compiler.

To get something that is equivalent, you might have something like this:

public class Foo {
    public Person Agent { get; }
}

Foo f = getFooFromWhereEver();
f.Agent.Name.ToString().ToLower();

In this case, imagine that Person has a property called Name which is a string. In this case, the chain of dots does four method invocations, at least one of which is virtual, but more likely than not all of these are invariant so calling them multiple times is redundant. I say 'more likely...' because that depends on the implementation of Agent and Person.

Problem

In the past, in C and C++ land, nested pointer dereferencing was considered, by some, to be a relatively expensive operation if executed in a tight loop. You wouldn't want to get caught with: ``` for (int i = 0; i < 10000000; i++) { j->k->l->m->n->o->p->dosomeworknowthatwereherewhynoteh(); } ``` because you might lose precious milliseconds. (Yes, I'm being somewhat sarcastic!) Moving to the world of .NET... Is this more expensive ``` System.Runtime.InteropServices.Marshal.WriteInt32(Abort, 1) ``` than this? ``` Imports System.Runtime.InteropServices.Marshal . . . WriteInt32(Abort, 1) ```

Original source