Virtual properties
When you declare a property in a class as virtual
, you allow classes derived from your class to override that property. However, this also slows down access to the property, because the compiler can no longer inline it.
This means that if you read the property a great many times, you can save some CPU cycles by copying it into a local variable and then accessing the local variable.
Take for example this class, which has one virtual
property:
private class MyClass { public virtual int IntProperty { get; set; } }
This code accesses the property a 1000 times:
int k = -1; for (int i = 0; i < 1000; i++) { k = myClass.IntProperty; }
This code copies the property into a local variable:
int k = -1; int j = myClass.IntProperty; for (int i = 0; i < 1000; i++) { k = j; }
Here are the test results on my machine:
Test |
Time taken (ticks) |
---|---|
Access property 1000 times |
51 |
Access local variable 1000 times |
19 |
You won't see this difference for non-virtual properties, because the compiler...