Thursday, 5 November 2015

ASP.NET Tips #46 - Eagerly create common object types to prevent constant evaluation

Many of us use code frequently in applications. For example:

if (myobject.GetType() == typeof(bool)) 
{ 
  // Do something 
}

-- Or --

if (myobject.GetType() == typeof()(MyCustomObject))
{ 
  // Do something 
}

Instead, consider eagerly creating these type of instances:

public static class CommonTypes
{
  public static readonly Type TypeOfBoolean = typeof(bool);
  public static readonly Type TypeOfString = typeof(string);
}

You can then do the following:

if (arg.GetType() == CommonTypes.TypeOfBoolean)
{
  // Do something
}

Or:

if (arg.GetType() == CommonTypes.TypeOfString)
{
  // Do something
}

And save the cost of performing the typeof(bool) or typeof(string) repeatedly in your code.

1 comment :

  1. Hi, I just test to validate this knowledge.

    In Debug build may be yes, but Release build is another way around. Using typeof() reduce time by half. May be .NET does some optimization when compiling in Release build.

    ReplyDelete