[.net] C# Fields vs. Properties
I am a strong advocate of clean C# class design, but I am curious of the performance disparity between fields and properties. I know that C# properties exist as a means of enforcing constraints on class fields, but I also know that they boil down to get_XXX and set_XXX functions in CIL and that in conventional programming function calls are more expensive operations than simply accessing a variable (similar idea to the theory behind the C++ "inline" keyword). I understand that both a general function call and a field access are extremely fast in the grand scheme. However, since I am building a graphics engine, I want EVERY bit of performance I can get. Within an "internal" context in my engine, could I gain any non-zero performance benefits by accessing fields directly instead of through properties?
If the property is just a simple field accessor, it should automatically get inlined and there should be no performance penalty.
Yes, the IL boils down to (with property name MyString) get_MyString and set_MyString, but the performance penality is not even worth worrying about. The design benefits from using properties are enormous though, and you should use them in order to promote a solid engine framework. There are way better performance issues you can consider than the vtable speed for properties vs fields. The biggest issue being your allocation profile and the pressure you have on the GC.
~Graham
~Graham
With Properties, you can change the code in the get/set function without invalidating the class's binary interface.
Also the JIT tends not to inline functions which are more than 20 IL long, so keep those property getters & setters short.
Also the JIT tends not to inline functions which are more than 20 IL long, so keep those property getters & setters short.
I like properties because I can use a field initially, and if validation becomes required, I can change to a property while maintaining source compatibility. FxCop gets pretty angry though.
A simple property, which just get or set a field will inline (just don't mark it virtual or such), so there should be no difference in performance.
source
source
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement