12 Replies - 9776 Views - Last Post: 08 January 2014 - 01:21 PM Rate Topic: -----

#1 macroer   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 17
  • Joined: 30-September 13

If Statement vs Switch Case vs Dictionary

Posted 07 January 2014 - 03:30 PM

Which one is the fastest for the program to run and maybe the one that takes up less CPU?

Also, which one is best to use depending on which situation?
Is This A Good Question/Topic? 0
  • +

Replies To: If Statement vs Switch Case vs Dictionary

#2 modi123_1   User is online

  • Suitor #2
  • member icon



Reputation: 15790
  • View blog
  • Posts: 63,277
  • Joined: 12-June 08

Re: If Statement vs Switch Case vs Dictionary

Posted 07 January 2014 - 03:33 PM

Ifs are less complex than a switch.. but switches can produce less complex code over all.

It is sort of an apples to pears comparison.

Quote

Also, which one is best to use depending on which situation?

What situations?
Was This Post Helpful? 0
  • +
  • -

#3 macroer   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 17
  • Joined: 30-September 13

Re: If Statement vs Switch Case vs Dictionary

Posted 07 January 2014 - 03:35 PM

View Postmodi123_1, on 07 January 2014 - 03:33 PM, said:

Ifs are less complex than a switch.. but switches can produce less complex code over all.

It is sort of an apples to pears comparison.

Quote

Also, which one is best to use depending on which situation?

What situations?

What is the best use for these situations?

If Statment:

Switch Case:

Dictionary:
Was This Post Helpful? 0
  • +
  • -

#4 modi123_1   User is online

  • Suitor #2
  • member icon



Reputation: 15790
  • View blog
  • Posts: 63,277
  • Joined: 12-June 08

Re: If Statement vs Switch Case vs Dictionary

Posted 07 January 2014 - 03:36 PM

Hmm.. what do you think? Let's see some effort before folks just do your homework for you.
Was This Post Helpful? 1
  • +
  • -

#5 macroer   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 17
  • Joined: 30-September 13

Re: If Statement vs Switch Case vs Dictionary

Posted 07 January 2014 - 03:38 PM

View Postmodi123_1, on 07 January 2014 - 03:36 PM, said:

Hmm.. what do you think? Let's see some effort before folks just do your homework for you.

I wasn't asking for code. I just wanted to know which are the best situations to use one of the commands.
Was This Post Helpful? 0
  • +
  • -

#6 modi123_1   User is online

  • Suitor #2
  • member icon



Reputation: 15790
  • View blog
  • Posts: 63,277
  • Joined: 12-June 08

Re: If Statement vs Switch Case vs Dictionary

Posted 07 January 2014 - 03:39 PM

Okay and I am asking for your thoughts on the topic. You know.. what have you considered so far?
Was This Post Helpful? 0
  • +
  • -

#7 tlhIn`toq   User is offline

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6537
  • View blog
  • Posts: 14,450
  • Joined: 02-June 10

Re: If Statement vs Switch Case vs Dictionary

Posted 08 January 2014 - 06:12 AM

Macroer - What modi is suggesting is that you could very easily do your own tests on this rather than ask others to do them for you. I think that's what he means by "show some effort on your part."

You want to know which is faster. Ok. Write some code to do that test.
Start a high performance stop watch.
Loop through a 10 stage "if" check one million times.
End the timer.

Now do the same the same with a 10 stage "switch" block.

Compare your results.

Do the same with a dictionary.

Now was that so hard?
Was This Post Helpful? 0
  • +
  • -

#8 Charles:)   User is offline

  • D.I.C Regular

Reputation: 149
  • View blog
  • Posts: 359
  • Joined: 26-November 09

Re: If Statement vs Switch Case vs Dictionary

Posted 08 January 2014 - 06:16 AM

If you write a simple switch method, then copy it and convert the copy to use if-else to do the same thing, then disassemble the code, you'll see that MSIL has a dedicated instruction for switching and it produces slightly less code to do the same thing. For my extremely simple method I saved 2 bytes by using a switch, but if you expand that up to an enterprise level solution then you could make significant savings in the code size by always using switches when appropriate.

If you think that the JIT needs to compile all of the code that's used, and that code needs to be held in memory, paged to disk etc. then code size can be important.

If you just want to know the comparison of run-time speeds then write some simple code and time it.
Was This Post Helpful? 1
  • +
  • -

#9 Curtis Rutland   User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 5106
  • View blog
  • Posts: 9,283
  • Joined: 08-June 10

Re: If Statement vs Switch Case vs Dictionary

Posted 08 January 2014 - 10:07 AM

I will answer the last question, because it seems to be based on a flawed premise. The question is, "Also, which one is best to use depending on which situation?" Unfortunately, this doesn't have a simple answer, because there are so many situations to be considered. The best answer is "use what makes semantic sense and gives you clean code". For instance, if you have to write half-a-dozen if-else statements, it's probably a good candidate for a switch statement. If your comparison only has two or three possible outcomes, if statements are simpler and easier to read. Dictionaries are a high-level construct (not a built-in keyword or operation) that aren't necessarily equivalent of ifs or switches. They map objects to keys. If you're going to need to pull items from a collection, and you can reference each with a unique key, that's a perfect use case for a Dictionary.

Notice how I never once mentioned performance? That's because it's not important for the vast majority of C# programs. So many people get themselves wrapped up in "which is faster?" that they miss the point of using high-level languages in the first place: programmer efficiency. The .NET runtime is very quick and most of the time, you won't notice the difference between different methods. The only time you have to worry about that is when you're dealing with massive sets or extremely CPU/Memory-intensive operations.

If you don't believe that, try it yourself. Look up the Stopwatch class (in System.Diagnostics) and use it to do some time tests. You'll see that the actual runtimes of these constructs is sub-millisecond. It's what you do with them that matters.

Side note: retrieving an item from a Dictionary is a O(1) operation, meaning there is no search time involved.
Was This Post Helpful? 1
  • +
  • -

#10 jon.kiparsky   User is offline

  • Beginner
  • member icon


Reputation: 11986
  • View blog
  • Posts: 20,312
  • Joined: 19-March 11

Re: If Statement vs Switch Case vs Dictionary

Posted 08 January 2014 - 10:29 AM

View PosttlhIn`toq, on 08 January 2014 - 08:12 AM, said:

Macroer - What modi is suggesting is that you could very easily do your own tests on this rather than ask others to do them for you. I think that's what he means by "show some effort on your part."

You want to know which is faster. Ok. Write some code to do that test.
Start a high performance stop watch.
Loop through a 10 stage "if" check one million times.
End the timer.

Now do the same the same with a 10 stage "switch" block.

Compare your results.

Do the same with a dictionary.

Now was that so hard?



Not to be pedantic, but this is not really a "best practices" approach to benchmarking a piece of software. :)/> I do like the "high performance stopwatch" concept - especially the idea of watching some kid in a white lab coat running iteration after iteration - but probably it's a better plan to get the system time directly from the machine.

As for execution times, it'll depend on the exact scenario - for example, how many cases are involved - but on the whole it's possible for the compiler to do better with a switch than with an if chain. This is because the switch can be compiled into a jump table, and the if chain cannot. I don't know how the "dictionary" is implemented in C#, but the usual approach for a key-value storage is some sort of hash table, which is quite fast for both storage and retrieval.

As far as programming practice goes, I prefer to use a lookup table whenever possible. This is not only fast and concise in terms of code, but also very easy to maintain, and depending on the data it can lend itself to more modular code. For example, if your keys and values are simple text-to-text or text-to-text lookups, say a phone directory or some such thing, you can read them in from an external document which can be maintained by someone who doesn't have access to the source code. For a switch or an if, of course, the key-vaue mappings can only be changed by altering the source code. So in many situations a dictionary can actually make your life easier by letting you offload work to the people better suited to doing it.

EDIT: Another rule of thumb which you might want to think about is, if you're using a switch or an if chain in an object-oriented language, you should probably stop and reconsider your design. It's probably wrong. (this is why modern languages don't generally have switches - although Scala's case constructor looks similar, it's a completely different construct and much more awesome)

This post has been edited by jon.kiparsky: 08 January 2014 - 10:32 AM

Was This Post Helpful? 0
  • +
  • -

#11 Curtis Rutland   User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 5106
  • View blog
  • Posts: 9,283
  • Joined: 08-June 10

Re: If Statement vs Switch Case vs Dictionary

Posted 08 January 2014 - 10:53 AM

View Postjon.kiparsky, on 08 January 2014 - 11:29 AM, said:

Not to be pedantic, but this is not really a "best practices" approach to benchmarking a piece of software. :)/>/> I do like the "high performance stopwatch" concept - especially the idea of watching some kid in a white lab coat running iteration after iteration - but probably it's a better plan to get the system time directly from the machine.


I believe what he meant by "high performance stopwatch" was the Stopwatch class in System.Diagnostics. Which would be getting the system time.
Was This Post Helpful? 0
  • +
  • -

#12 Momerath   User is offline

  • D.I.C Lover
  • member icon

Reputation: 1021
  • View blog
  • Posts: 2,463
  • Joined: 04-October 09

Re: If Statement vs Switch Case vs Dictionary

Posted 08 January 2014 - 11:39 AM

View PostCharles:), on 08 January 2014 - 05:16 AM, said:

you'll see that MSIL has a dedicated instruction for switching and it produces slightly less code to do the same thing.

Smaller MSIL code does not always translate to smaller compiled code as MSIL is not a 1 to 1 to assembly (or an 1 to c, where c is a constant). But in the case of switch vs if block, it depends on what you are switching on. For example this code
switch (a) {
    case 1: Console.WriteLine(1); break;
    case 2: Console.WriteLine(2); break;
    case 3: Console.WriteLine(3); break;
    case 4: Console.WriteLine(4); break;
    default: Console.WriteLine(0); break;
}

if (a == 1) Console.WriteLine(1);
else if (a == 2) Console.WriteLine(2);
else if (a == 3) Console.WriteLine(3);
else if (a == 4) Console.WriteLine(4);
else Console.WriteLine(0);

This code results in 94 bytes for the switch, and 93 for the if/else*. At first thought you'd think the if/else would be faster, but the instructions used are more costly in execution time, and, on average, more of the 93 bytes are executed than the 94 for the switch statement.

If we substitute strings instead of numbers (for the switch and compare, still using numbers for output so that won't affect the size) we get 170 for the switch and 146 for the if. In this case, the interior code is almost identical except that the switch has more jump instructions and the location of the instructions (what I mean by this is that the switch does all the tests up front, then the actual code below that, while the if does the test then the code. In pseudo code:
switch
    is it an "a"?
    If yes, go to 1
    is it a "b"?
    if yes, go to 2
    etc...
1   print 1
    go to end
2   print 2
    go to end
    etc...
end done

vs.
if it is an "a"
    print 1
    go to end
    if it is a "b"
    print 2
    go to end
    etc.
end done
)

tl;dr: MSIL doesn't translate 1 to 1 to assembly. Byte counts alone won't tell you which is faster.

* - On my machine using VS 2012 Professional, 32bit, release mode. YMMV. Void where prohibited.

This post has been edited by Momerath: 08 January 2014 - 11:44 AM
Reason for edit:: Corrected the note, cheap workplace machines are only 32 bit, not 64 bit. Nor does my work pay for Ultimate.

Was This Post Helpful? 2
  • +
  • -

#13 AdamSpeight2008   User is offline

  • MrCupOfT
  • member icon

Reputation: 2298
  • View blog
  • Posts: 9,535
  • Joined: 29-May 08

Re: If Statement vs Switch Case vs Dictionary

Posted 08 January 2014 - 01:21 PM

It sort of depends on the number of items. After a certain number it compile into a dictionary lookup.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1