O'Reilly logo

ASP.NET Site Performance Secrets by Matt Perdeck

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required