开发者

How does method inlining work for auto-properties in C#?

I'm reading Effective C# (Second Edition) and it talks about method inlining.

I understand the principle, but I don't see how it would work base开发者_开发百科d on the 2 examples in the book. The book says:

Inlining means to substitute the body of a function for the function call.

Fair enough, so if I have a method, and its call:

public string SayHiTo(string name)
{
    return "Hi " + name;
}

public void Welcome()
{
    var msg = SayHiTo("Sergi");
}

the JIT compiler might (will?) inline it to:

public void Welcome()
{
    var msg = "Hi " + "Sergi";
}

Now, with these two examples (verbatim from the book):

Example 1

// readonly name property
public string Name { get; private set; }

// access:
string val = Obj.Name;

Example 2

string val = "Default Name";
if(Obj != null)
    val = Obj.Name;

The book mentions the code but doesn't go any further into how they might be inlined. How would the JIT compiler inline these 2 examples?


Automatic properties are syntactic sugar for field-backed properties.

Properties are syntactic sugar for setter and/or getter methods.

Hence the code you give is more or less equivalent to:

private string _name;
public string get_Name()
{
  return _name;
}
private void set_Name(string value)
{
  _name = value;
}

Then string val = Obj.Name becomes equivalent to string val = Obj.get_Name() which can be inlined to string val = Obj._name.

Likewise the code

string val = "Default Name";
if(Obj != null)
  val = Obj.Name;

Is is equivalent to:

string val = "Default Name";
if(Obj != null)
  val = Obj.get_Name();

Which can be inlined to:

string val = "Default Name";
if(Obj != null)
  val = Obj._name;

Note that private and public apply to compilation, not to execution, so while the fact that the backing field is private would make Obj._name illegal outside of the class in question, the equivalent code produced by inlining, is allowed.


Hypothetically speaking, inlining here would unwrap the body of get_Name() that's auto-generated by the compiler, which simply returns a private backing field. It might look something like this:

string val = Obj.k__BackingField;


Inlining takes places after accessibility checks, so it can optimize code in ways that you can't with simple source substitution.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜