What is wrong with Enum.ToString()?

This morning, while we where working on the creation of Key/Value pair table containing different kind of entities one of my senior team meber ran into an “Exotic” behavior. The key of our table is a string build on the composition of the entity Id and the entity type. The entity type is simply an enum value converted to a string. This looked like this:

_ToString = string.Format(“[{0}/{1}]”, id, contactType.ToString());

contact type is here the enum variable. Nothing really fancy or complicate untill we ran the performance monitor on it.

We saw that this line, according to its simplicity was taken too much time to  process.

We have to perform this operation for millions of records and every millisecond counts.

At first sight I though it was the string.Format() that was taking all the processing and we tried a quick optimization.

_ToString = “[” +  id + “/” + contactType.ToString() + “]”;

Same result. I had to face it, the ToString() of the enum variable was taking most of the processing.

The number of entries in enum being short, we tried the following code

switch (contactType)

{

    case ContactTypeEnum.Undefined:

        _ToString = “[” + id + “/Undefined]”;

        break;

    case ContactTypeEnum.Organisation:

        _ToString = “[” + id + “/Organisation]”;

        break;

    case ContactTypeEnum.NaturalPerson:

        _ToString = “[” + id + “/NaturalPerson]”;

        break;

    case ContactTypeEnum.OrganisationContact:

        _ToString = “[” + id + “/OrganisationContact]”;

        break;

    default:

        throw new ArgumentOutOfRangeException(“contactType”);

}

The difference was impressive. This long piece of code is almost 8 time faster.

The following image gives the performance numbers of each of the code block.

 

 

One thought on “What is wrong with Enum.ToString()?

  1. Gaston

    A problem with the “long code” is that if you add a value to your enumerator, you musn’t forget to add it there as well.
    In general you’d only need enum.ToString() in rare cases (like presenting the value to a user), so the performance of this function isn’t so important.

    An advantage of the “long code” is that you can localize your enums.

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s