Getting Flags

When checking if an enum that is a flags enum has a value set, you may wish to use either of two methods:

if ((ve & ValuesEnum.One) != 0)

or

if ((ve & ValuesEnum.One) == ValuesEnum.One)

I always use the first version. It seems faster. I did, however, mean to check it for a while now. This is what I came up with:

Method 1:

Tested code:

ValuesEnum ve = ValuesEnum.One;
if ((ve & ValuesEnum.One) != 0)
{
ve = ValuesEnum.Two;
}

Output IL:

IL_0000:  ldc.i4.1
IL_0001:  stloc.0
IL_0002:  ldloc.0
IL_0003:  ldc.i4.1
IL_0004:  and
IL_0005:  brfalse.s  IL_0009
IL_0007:  ldc.i4.2
IL_0008:  stloc.0
IL_0009:  ret

Time for 200,000,000 runs: 4.3963216 seconds.

Method 2:

Tested code:

ValuesEnum ve = ValuesEnum.One;
if ((ve & ValuesEnum.One) == ValuesEnum.One)
{
ve = ValuesEnum.Two;
}

Output IL:

IL_0000:  ldc.i4.1
IL_0001:  stloc.0
IL_0002:  ldloc.0
IL_0003:  ldc.i4.1
IL_0004:  and
IL_0005:  ldc.i4.1
IL_0006:  bne.un.s   IL_000a
IL_0008:  ldc.i4.2
IL_0009:  stloc.0
IL_000a:  ret

Time for 200,000,000 runs: 4.8970416 seconds.

Conclusions:

  1. My computer sucks, as Ido keeps reminding me.
  2. We get two commands with the second version. One to load ValuesEnum.One again and the other to compare the result of the And operation. The first version has only one that compares it to zero (it’s a build in command).
  3. The first version is faster by a very very very very very small amount.
Advertisements

2 thoughts on “Getting Flags

  1. You’re timing the whole method but you’re interpreting the results as if only the check ran. Half of the code is not relevant to the flag check so you should exclude it from your test. It’s probably closer to 2.3 and 2.8 seconds (the rest is loading up ve, constant and not relevant to your test) and that’s a lot larger difference, roughly 20% speedup which can be very significant.

  2. Jerry,
    1. I actually ran the method once prior to the loop for JIT optmisiations.
    2. I don’t care that there’s more code than just the code I tested, because it is the exact same code and runs at the exact same speed. The only location where a difference could be made is the changed lines.

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