Gururaj’s Rumination

Rumination – The word says it all…

Posts Tagged ‘.NET

Enum.IsDefined and Performance issue

with 2 comments

Till today I’d never used Enum.IsDefined method to verify whether a value is defined in a given Enum. My first encounter with Enum.IsDefined happened a day or two before when I stumbled on this while analyzing existing code for performance loopholes. I found a method which happened to verify whether a value is defined in the given Enum and flag if it’s not. I’d never imagined that Enum.IsDefined can be so expensive that the performance of the component will go down exponentially based on the volume of the data it has to process. To understand better why it’s expensive lets first understand Enum.

Enum is a ValueType and every Enum derives implicitly from System.Enum and this in turn derives from ValueType. To understand in more detail here is the extracted description from the C# Language Specification

11.1.9 Enumeration types

An enumeration type is a distinct type with named constants. Every enumeration type has an underlying type, which shall be byte, sbyte, short, ushort, int, uint, long or ulong. Enumeration types are defined through enumeration declarations (§21.1). The direct base type of every enumeration type is the class System.Enum. The direct base class of System.Enum is System.ValueType.

Given the definition, the below code snippet declares a ‘Status’ enum type. And from definition the underlying type of ‘Status’ type will be Int32. This means that ‘InProgress’ is named a constant for value 0 and ‘Success’ is named constant for value 1 followed by ‘Failed’ as 2. The point to be noted here is that the first named constant always starts with 0 and the subsequent constants have incremental value.

                enum Status

Read the rest of this entry »

Written by Gururaj

December 24, 2008 at 9:57 pm

Posted in Technology

Tagged with , ,