Does C# inline properties? - c#

Does C# inline access to properties? I'm aware of the 32 byte (instruction?) limit on the JIT for inlining, but will it inline properties or just pure method calls?

It's up to the JIT (the C# compiler doesn't do any inlining as far as I'm aware), but I believe the JIT will inline trivial properties in most cases.
Note that it won't inline members of types deriving from MarshalByRefObject which includes System.Windows.Forms.Control (via System.ComponentModel.Component).
I've also seen double fields end up being less efficient when accessed via properties - it could be that there are some subtleties around that (due to register use etc).
Also note that the 64-bit and 32-bit JITs are different, including their treatment of what gets inlined.
EDIT: I've just found a 2004 blog entry by David Notario with some more information. However, that was before 2.0 shipped - I wouldn't be surprised to see that at least some of it had changed now. Might be of interest anyway.
EDIT: Another question referred to a 2008 Vance Morrison blog entry which gives more information. Interesting stuff.

A property access is just a pure method call. There is no difference in the IL the compiler emits for a property access and for a method call with a similar signature, which sort of answers your question.

It took me a while to figure out that in Visual Studio you can view the disassembly of managed code, after the JIT compiles it.
So why not create a class with a very simple accessor property, run it in release mode, set a breakpoint, and see what the disassembly says?

I posted a similar question recently:
Why are public fields faster than properties?
The issue with mine was that a public field was faster than a property because I'm running 64-bit Vista and the JIT compiled my code to 64-bit as well, and my properties were not in-lined. Forcing the project to compile for x86 did in-line the property and there was no speed difference between the property and the public field.
So, the C# 32-bit JIT does in-line properties, the 64-bit doesn't, nor any other non-static methods.

Related

Properties slower than fields

It seems that every post I have come across comes to the same consensus: properties that merely return a field are inlined by JIT and have nearly identical performance to fields.
However, this doesn't seem to be the case with my current scenario. My program does intensive calculations that access many properties that are simply auto-getters and private setters. In this particular case, however, I am just copying an object.
Profiling the code in release mode with optimizations enabled resulted in many calls to the get functions of the property. The calls to Copy() total up to ~5.6ms.
However, when the properties are converted into fields, the function runs 6x faster than it did with properties:
Comparing equality of two properties seems to incur even more of a performance hit compared to using fields. Here's a benchmark of a class's IEquatable implementation, using the same code but swapping properties with fields.
If JIT is supposed to optimize properties by inlining them, why is this occuring? I would like to keep properties, as the access control aspect of them is very convenient, but if they are this much slower I will stick to fields.
EDIT: It seems like some (but not all) cases affected by this problem are using properties declared in interfaces. No other polymorphism is being used in these cases, but removing the interface brings the performance variance into expected levels in these cases.
EDIT 2: As stated in the previous edit, it seems that a part of the problem was due to Interface virtual calls. After more investigation, it seems that running a benchmark in the CLR properly inlines properties, but JetBrains dotTrace does not, even with "Enable inline" checked.
Unfortunately the is not much more you can do except try to help the JITTER out by using
[MethodImpl(MethodImplOptions.AggressiveInlining)]
AggressiveInlining The method should be inlined if possible.
Now technically this can only be used on a method or construtor, however you can seemingly test it on the getters and setters them selves. ie it compiles (i haven't tested this though)
public int someType
{
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
get;
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
set;
}
Note : in-lining is a blackbox of wonderment, the jitter may feel like it or not, even the attribute is only a suggestion. also note that the bitness may also affect what it inlines.
Lastly, i think you are going about this the right way, you should just use a bechmarker or profiler, and micro-optimize accordingly,

Why does "dynamic" require language-specific runtime components?

Microsoft.CSharp is required to use dynamic feature.
I understand there are binders, evaluators and helpers in the assembly.
But why it has to be language-specific?
Why Microsoft.CSharp and not Microsoft.Dynamic or System.Dynamic?
Please, explain.
Let's say we have d.x where d is dynamic.
C# compiler
1. applies C# language rules
2. gets "property or field access"
3. emits (figurally) Binder.GetPropertyOrField(d, "x")
Now, being asked to reference Microsoft.CSharp may make one think that language-agnostic binder can't handle this case, and C#-only something got its way through compilation and requires special library.
Compiler had a bad day?
To your first question, it is language-specific because it needs to be.
In C# you call a method with too many arguments and you get an error. In Javascript, the extra arguments are simply ignored. In C# you access a member that doesn't exist and get an error, while in Javascript you get undefined. Even if you discovered all these varying feature sets and put it all into System.Core, the next language fad of the month is sure to have some super neat feature that it wouldn't support. It's better to be flexible.
There is common code in .NET core, under the System.Dynamic and System.Runtime.CompilerServices namespaces. It just can't all be common.
And as for your second question, the need for the "special C# library" could of course be removed by transforming these language-specific behaviors inline, but why? That will needlessly bloat your IL code size. It is the same reasoning for you not writing your own Int32.Parse every time you need to read in a number.
One reason I can think of - Visual Basic.NET has had late binding in it from day one, primarily oriented around how it interoperates with COM IDispatch interfaces - so if they wanted a language agnostic binder, they'd have had to adopt the Visual Basic rules - which includes that member lookup only works with Public members.
Apparently, the C# designers didn't want to be so strict. You can call this class' DoStuff method from C# via a dynamic reference:
public class Class1
{
internal void DoStuff()
{
Console.WriteLine("Hello");
}
}
Whereas attempting to call the same via Visual Basic's Object results in a MissingMemberException at runtime.
So because the C# designers weren't the first to arrive at the late-binding party, they could either follow Visual Basic's lead or they could say "each language will have its own rules" - they went with the latter.

c# generics Turing-complete? [duplicate]

There is a well-known fact that C++ templates are turing-complete, CSS is turing-complete (!) and that the C# overload resolution is NP-hard (even without generics).
But is C# 4.0 (with co/contravariance, generics etc) compile-time turing complete?
Unlike templates in C++, generics in C# (and other .net lang) are a runtime generated feature. The compiler does do some checking as to verify the types use but, actual substitution happens at runtime. Same goes for Co and contravariance if I'm not mistaken as well as even the preprocessor directives. Lots of CLR magic.
(At the implementation level, the primary difference is that C#
generic type substitutions are performed at runtime and generic type
information is thereby preserved for instantiated objects)
See MSDN
http://msdn.microsoft.com/en-us/library/c6cyy67b(v=vs.110).aspx
Update:
The CLR does preform type checking via information stored in the metadata associated with the compiled assemblies(Vis-à-vis Jit Compliation), It does this as one of its many services,(ShuggyCoUk answer on this question explains it in detail) (others include memory management and exception handling). So with that I would infer that the compiler has a understanding of state as progression and state as in machine internal state (TC,in part, mean being able to review data (symbols) with so reference to previous data(symbols) , conditionally and evaluate) (I hesitated to state the exact def of TC as I, myself am not sure I have it fully grasped, so feel free to fill in the blanks and correct me when applicable ) So with that I would say with a bit of trepidation, yes, yes it can be.

C# Compiler optimization - Unused methods

Does C# compiler (in VS2008 or VS2010) remove unused methods while compiling ?
I assume that it may have a problem deciding if public methods will ever be used, so I guess it will compile all the public methods.
But what about private methods that are never used inside a class ?
EDIT:
Are there a set of rules about the compiler's optmization that are documented anywhere ?
Just checked in reflector with a release build. The compiler doesn't remove the unused private methods.
There are ways to use a method without the compiler knowledge, like with reflection. So the compiler doesn't try to guess. It just leaves the methods there.
The only private methods the compiler removes are partial methods without implementation.
For the C# compiler optimizations, look here (archive.org).
The compiler doesn't strip any method from the assembly, public or private. I could in fact cause weird issues with reflection, and prevent runtime calls to such methods.
There are a lot of frameworks (like the XAML parser) which enable you to call private methods without static bindings (think about OnClick="myFunction" in a XAML file) This markup will call the potentially private myFunction when the OnClick event is raised... But the compiler has no informations about such a behavior at compile time.
Dynamic code suffer from the same issue, IL generation too. And you can access private methods from any object when executing under full trust.
This optimization is effectively implemented at the JIT level, which is good because then it works for both public/private/whatever methods. If a method is never called (ignoring ngen, etc.), it never gets JITed. Now you might say that this is still a waste of space for metadata etc. but as others have pointed out, private isn't so private.
No they won't be removed. It may give you warning for that but won't do it itself.

How to use ResourceExposureAttribute and ResourceConsumptionAttribute?

I have found the attribute ResourceExposureAttribute and ResourceConsumptionAttribute in the DefaultTraceListener.
When are used? Are they read by the framework or should be considered by the programmer? More, what are the differences between them?
These attributes are declared with a ConditionalAttribute, meaning that the compiler shouldn't include them in the final source code unless the conditional (in this case RESOURCE_ANNOTATION_WORK) is defined. It appears that these attributes are for some static analysis tool, internal to the .NET development team, to run over a special build of the Framework for some purpose. It's not clear what that purpose is. Something to do with side-by-side loading of two versions of the Framework in the same process.
ResourceConsumption seems to be the basic attribute, indicating that this class or method consumes some form of resource beyond just ordinary memory, and whether this is a per-process or per-machine resource that is consumed. ResourceExposure seems to indicate that the class or method wraps that resource for consumption by other classes or methods.
I encountered the attributes when looking at the source code for Font and FontFamily, but there are many, many classes which are annotated with them. I don't think it's useful for any code you write to add the attributes, because they won't get compiled in unless you specifically opt in to doing so, and you don't have the tool to analyze the results.

Categories

Resources