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;
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)
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 ...
%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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With