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 ...

Get ASP.NET Site Performance Secrets now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.