Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the C# or JIT compiler smart enough to handle this?

Assuming we have the following model:

public class Father
{
    public Child Child { get; set; }
    public string Name { get; set; }

    public Father() { }
}

public class Child
{
    public Father Father;
    public string Name { get; set; }
}

And the following implementation:

var father = new Father();
father.Name = "Brad";
var child = new Child();
child.Father = father;
child.Name = "Brian";
father.Child = child;

Now my question: Is codesnippet #1 equivalent to codesnippet #2?

Or does it take longer to run codesnippet #1?

CodeSnippet #1:

var fatherName = father.Child.Father.Child.Father.Child.Name;

CodeSnippet #2:

var fatherName = father.Name;
like image 922
Fabian Bigler Avatar asked Jun 27 '13 10:06

Fabian Bigler


People also ask

Is there a C+?

C+ (grade), an academic grade. C++, a programming language. C with Classes, predecessor to the C++ programming language. ANSI C, a programming language (as opposed to K&R C)

What is C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What does %c mean in C?

%d is used to print decimal(integer) number ,while %c is used to print character . If you try to print a character with %d format the computer will print the ASCII code of the character.


1 Answers

The C# compiler will not optimize this, and will emit just all operations for calling the property getters.

The JIT compiler on the other hand, might do a better job by inlining those method calls, but won't be able to optimize this any further, because it has no knowledge of your domain. Optimizing this could theorethically lead to wrong results, since your object graph could be constructed as follows:

var father = new Father
{
    Child = new Child
    {
        Father = new Father
        {
            Child = new Child
            {
                Father = new Father { ... }
            }
        }
    };

Or does it take longer to run codesnippet #1?

The answer is "Yes", it would take longer to run the first code snippet, because neither C# nor the JIT can optimize this away.

like image 148
Steven Avatar answered Sep 20 '22 13:09

Steven