5

My teacher asked us to make a program in the most efficient way possible and to use a switch case for this.

The program asks the user for input, and depending on what the user inputs, the program will have to follow a set of instructions.

If the input is "A" or "a", the array has to be sorted from A to Z.

If the input is "Z" or "z", the array has to be sorted from Z to A.

If the input is "R" or "r", the array has to be reversed.

The array is a string[].

So I'm wondering if it's more effecient to use

switch (choice.ToLower())
{
    case "a":
        Array.Sort(array);
        break;
    case "z":
        Array.Sort(array);
        Array.Reverse(array);
        break;
    case "r":
        Array.Reverse(array);
        break;
}

or

 if (choice.ToLower() == "a" || choice.ToLower() == "z")
 {
     Array.Sort(array);
 }

 if (choice.ToLower() == "r" || choice.ToLower() == "z")
 {
     Array.Reverse(array);
 }

and also if this code can be optimised even further.

So, is the most efficient way to use a switch case, or the if structure as seen above and explain why?

I'm just curious since I always try to optimise all my code to full extent.

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
  • 2
    first one is more efficient because it calls ToLower once. but they both compile into if-else. in compiled code with switch `choice.ToLower()` is saved in local variable and its value is checked over if-else. however the second version it is possible that ToLower method gets called from 1 time to 4 times. – M.kazem Akhgary Oct 10 '15 at 17:16
  • 1
    At least sorting directly to reverse order would be faster than sort and reverse, if you also care about that – Sami Kuhmonen Oct 10 '15 at 17:19
  • Have you tried benchmarking it? – rhens Oct 10 '15 at 17:19
  • functionally, these two are equivalent; However, if the point of the exercise was to use a switch statement, then that should be your focus. You may want to read http://meta.programmers.stackexchange.com/questions/6166/open-letter-to-students-with-homework-problems. It's an older post, but the sentiment still applies. When learning, performance should be your least important factor. – Claies Oct 10 '15 at 17:19
  • So, if I'd store the choice.ToLower in choice before executing the code, then leave out the ToLower in the if structure, would that execute faster? – Jesse Verbruggen Oct 10 '15 at 17:29
  • @Claies We already went over the switch case thing, the point of the exercise was displaying arrays, but our teacher hinted towards the use of switch case, but i tried to see if my idea wasn't better. – Jesse Verbruggen Oct 10 '15 at 17:41
  • @JesseVerbruggen Please don't change your question's code. This makes the comments you got make less sense. – Lee Taylor Oct 10 '15 at 19:37

3 Answers3

6

Well, you can check it by yourself :

class Program
{
    static void MyMethod1(int[] array, string choice)
    {            
        switch (choice.ToLower())
        {
            case "a":
                Array.Sort(array);
                break;
            case "z":
                Array.Sort(array);
                Array.Reverse(array);
                break;
            case "r":
                Array.Reverse(array);
                break;
        }
    }

    static void MyMethod2(int[] array, string choice)
    {            
        if (choice.ToLower() == "a" || choice.ToLower() == "z")
        {
            Array.Sort(array);
        }

        if (choice.ToLower() == "r" || choice.ToLower() == "z")
        {
            Array.Reverse(array);
        }
    }

    static int[][] CreateRandomArrays(int num, int length)
    {
        Random rand = new Random();
        int[][] arrays = new int[num][];

        for (int i = 0; i < arrays.Length; i++)
        {
            arrays[i] = new int[length];
            for (int i2 = 0; i2 < length; i2++)
                arrays[i][i2] = rand.Next();
        }

        return arrays;
    }

    static void Main(string[] args)
    {
        int[][] test1 = CreateRandomArrays(50, 200000);
        int[][] test2 = CreateRandomArrays(50, 200000);

        Stopwatch s = new Stopwatch();

        s.Start();

        for (int i = 0; i < test1.Length; i++) MyMethod1(test1[i], "z");

        s.Stop();
        Console.WriteLine(s.ElapsedMilliseconds);

        s.Restart();            

        for (int i = 0; i < test2.Length; i++) MyMethod2(test2[i], "z");

        s.Stop();

        Console.WriteLine(s.ElapsedMilliseconds);
    }
}

As you can see result is almost identical :

1010 ms    vs    1008 ms
Fabjan
  • 13,506
  • 4
  • 25
  • 52
  • This was very helpful code, thank you, My results when changing the choice.ToLower in the if structure so it would only be called once resulted in: 1749 ms vs 1694 ms – Jesse Verbruggen Oct 10 '15 at 17:38
  • @JesseVerbruggen By all means. Feel free to experiment with this simple benchmark to test performance... Also as others said `ToUpper()` is better then `ToLower()`. I'd suggest that 99% of time execution for both of these methods is required for `Sort()` and `Reverse()` methods and not `if` or `switch` statements – Fabjan Oct 10 '15 at 18:20
1

ToUpper is faster + using Linq, ordering things will not be executed till join part...

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static string[] words = {
        "what", "is", "the", "most", "effecient", "way", "to", "execute", "this", "code"
    };

    static void Main(string[] args)
    {
        IEnumerable<string> result;

        Console.Write("Choose words order (A to Z (A), Z to A (Z), Reversed (R)): ");

        switch (Console.ReadLine().ToUpper())
        {
            case "A": result = words.OrderBy(w => w); break;
            case "Z": result = words.OrderByDescending(w => w); break;
            case "R": result = words.Reverse(); break;
            default: result = words.AsEnumerable(); break;
        }

        Console.WriteLine(string.Join(" ", result));
    }
}
Matěj Pokorný
  • 16,977
  • 5
  • 39
  • 48
0

In your case if is slower because every time it check 2 conditions. Check also this article about switch vs if speed. (in your example with the if's 4 conditions are always checked).
If a switch contains more than five elements, it's implemented using a lookup table or a hash list which means that all items get the same access time, compared to a list of if's where the last item takes much more time to reach as it has to evaluate every previous condition first.

CDrosos
  • 2,418
  • 4
  • 26
  • 49