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.
Compiler: The compiled languages are always going to be faster than interpreted languages. The compiler compiles all of the code into executable machine code at once, whereas the interpreter scans the program line by line and converts it into machine code. So it delays the execution time for interpreters.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With