执行此代码的最有效方法是什么?

时间:2022-10-22 10:33:50

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.

如果输入为“A”或“a”,则必须从A到Z对数组进行排序。

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

如果输入为“Z”或“z”,则数组必须从Z到A排序。

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

如果输入为“R”或“r”,则必须反转数组。

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?

那么,是使用开关案例的最有效方式,还是如上所示的if结构并解释原因?

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

我很好奇,因为我总是试图完全优化我的所有代码。

3 个解决方案

#1


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

#2


1  

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

ToUpper更快+使用Linq,订购的东西在加入部分之前不会被执行...

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));
    }
}

#3


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.

在你的情况下,如果速度较慢,因为每次检查2个条件。还请查看本文关于switch vs if speed的信息。 (在您的示例中,始终检查if的4个条件)。如果一个开关包含五个以上的元素,那么它是使用查找表或哈希列表实现的,这意味着所有项目都获得相同的访问时间,相比之下,如果最后一个项目需要花费更多时间,那么所有项目都必须达到首先评估每个先前的条件。

#1


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

#2


1  

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

ToUpper更快+使用Linq,订购的东西在加入部分之前不会被执行...

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));
    }
}

#3


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.

在你的情况下,如果速度较慢,因为每次检查2个条件。还请查看本文关于switch vs if speed的信息。 (在您的示例中,始终检查if的4个条件)。如果一个开关包含五个以上的元素,那么它是使用查找表或哈希列表实现的,这意味着所有项目都获得相同的访问时间,相比之下,如果最后一个项目需要花费更多时间,那么所有项目都必须达到首先评估每个先前的条件。