If vs Ternary: Deathmatch

1: INTRO

The Fun With the ?? Operator in C#: if { } or ?? – Which is Faster? article by Keith Elder got me thinking about the if statement and the ternary operator.

Is there a real difference or are they both the same?

To answer this question I put together a little project that tests both cases and times them.

2: CODE

using System;
using System.Diagnostics;
 
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
 
            string[] strArray = new string[20000];
            Random r = new Random((int)DateTime.Now.Ticks);
            for (int i = 0; i < 500; i++)
            {
                int rnum = r.Next();
                if (rnum % 2 == 0)
                {
                    strArray[i] = null;
                }
                else
                {
                    strArray[i] = rnum.ToString();
                }
            }
 
            TimeSpan ts1 = TimeSpan.Zero;
            TimeSpan ts2 = TimeSpan.Zero;
 
            for (int i = 0; i < strArray.Length; i++)
            {
                ts2 = ts2.Add(countWithTernary(strArray));
                ts1 = ts1.Add(countWithIf(strArray));
            }
 
            for (int i = 0; i < strArray.Length; i++)
            {
                ts1 = ts1.Add(countWithIf(strArray));
                ts2 = ts2.Add(countWithTernary(strArray));
            }
 
            Console.WriteLine("     if: " + ts1.TotalMilliseconds.ToString());
            Console.WriteLine("ternary: " + ts2.TotalMilliseconds.ToString());
            Console.ReadLine();
        }
 
 
        private static TimeSpan countWithIf(string[] arr)
        {
            Stopwatch sw = new Stopwatch();
            int len = arr.Length;
            int count = 0;
            sw.Start();
            for (int i = 0; i < len; i++)
            {
                if (arr[i] == null)
                {
                    count += 1;
                }
                else
                {
                    count += 2;
                }
            }
            sw.Stop();
            return sw.Elapsed;
        }
 
        private static TimeSpan countWithTernary(string[] arr)
        {
            Stopwatch sw = new Stopwatch();
            int len = arr.Length;
            int count = 0;
            sw.Start();
            for (int i = 0; i < len; i++)
            {
                count += arr[i] == null ? 1 : 2;
            }
            sw.Stop();
            return sw.Elapsed;
        }
    }
}

3: RESULTS

The output of the above code suprised me, here are the results:

Here we see that using the if statement is much faster than the ternary operator.

In release the if statement gets faster and the ternary stays about the same.

Surprising to me here was when compiled with x64 the if statement was just as slow (or even slower) than the ternary one.

In release for the x64 they're both almost the same again but the ternary operation is faster than the x86 version.

4: CONCLUSION

In conclusion i think using the if statement would be faster in most cases although in most applications the difference would be unnoticeable.

AttachmentSize
ifternarydeathmatch.zip62.56 KB
Your rating: None Average: 2.3 (8 votes)

Comments

So I am guessing that you

So I am guessing that you will be removing all of the ternary operators from your code. Which would be a shame. I like the 1000 character long lines of code.

Funny

I'll probably use them less, but not going to go back and remove them all.

Post new comment

The content of this field is kept private and will not be shown publicly.
 
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <c>, <cpp>, <csharp>, <css>, <drupal5>, <drupal6>, <java>, <javascript>, <objc>, <php>, <python>, <ruby>, <tsql>. The supported tag styles are: <foo>, [foo].

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.