If vs Ternary: Deathmatch

Share this

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
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)

Hi, preseeExtesed

Hi, preseeExtesed http://www.bearmania.net/ - provigil online no prescription Additionally, doctors will prescribe Provigil for the treatment of spastic cerebral palsy, Parkinson?s disease, opiod induced sleepiness, myotonic dystrophy, chronic fatigue syndrome, as well as fibromyalgia. http://www.bearmania.net/ - buy provigil online

Nicotine In Drug Tests

Nicotine In Drug Tests http://www.thesweetspotcafe.com/ - order ambien Get the help that you need today. http://www.thesweetspotcafe.com/ - cheap ambien online

Drug Alcohol Recovery Process

Drug Alcohol Recovery Process http://www.highlandgatesonkatytrail.com/ - buying valium online Buy Valium online without prescription. http://www.highlandgatesonkatytrail.com/ - cheap valium online

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> <img>
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <asp>, <c>, <cpp>, <csharp>, <css>, <drupal5>, <drupal6>, <html4strict>, <java>, <javascript>, <objc>, <php>, <python>, <ruby>, <tsql>.

More information about formatting options

By submitting this form, you accept the Mollom privacy policy.