Information Technology Reference
In-Depth Information
Of course, you would never do that because you know better than to cre-
ate public data members (see Item 1). The JIT compiler understands your
need for both efficiency and elegance, so it inlines the property accessor.
The JIT compiler inlines methods when the speed or size benefits (or both)
make it advantageous to replace a function call with the body of the called
function. The standard does not define the exact rules for inlining, and
any implementation could change in the future. Moreover, it's not your
responsibility to inline functions. The C# language does not even provide
you with a keyword to give a hint to the compiler that a method should be
inlined. In fact, the C# compiler does not provide any hints to the JIT com-
piler regarding inlining. (You can request that a method not be inlined
using the System.Runtime.CompilerServices.MethodImpl attribute, spec-
ifying the NoInlining option. It's typically done to preserve method names
on the callstack for debugging scenarios.)
[ MethodImpl ( MethodImplOptions .NoInlining)]
All you can do is ensure that your code is as clear as possible, to make it eas-
ier for the JIT compiler to make the best decision possible. The recom-
mendation should be getting familiar by now: Smaller methods are better
candidates for inlining. But remember that even small functions that are
virtual or that contain try / catch blocks cannot be inlined.
Inlining modifies the principle that code gets JITed when it will be exe-
cuted. Consider accessing the name property again:
string val = "Default Name" ;
if (Obj != null )
val = Obj.Name;
If the JIT compiler inlines the property accessor, it must JIT that code
when the containing method is called.
This recommendation to build smaller and composable methods takes on
greater importance in the world of LINQ queries and functional pro-
gramming. All the LINQ query methods are rather small. Also, most of
the predicates, actions, and functions passed to LINQ queries will be small
blocks of code. This small, more composable nature means that those
methods, and your actions, predicates, and functions, are all more easily
reused. In addition, the JIT compiler has a better chance of optimizing
that code to create more efficient runtime execution.
 
Search WWH ::




Custom Search