【问题标题】:Store as variable vs without存储为变量 vs 没有
【发布时间】:2016-02-15 06:28:23
【问题描述】:

下面这两种方法,有什么区别吗?抛开代码可读性不谈,Method1 会消耗更少的内存,而Method2 执行得更快吗?

一般来说,我应该总是使用哪一个?

    public void Method1(string userInput)
    {
        if (userInput.ToLower().Replace(" ", "") == "optiona")
        {

        }

        else if (userInput.ToLower().Replace(" ", "") == "optionb")
        {

        }

        else
        {

        }
    }

    public void Method2(string userInput)
    {
        string modifiedInput = userInput.ToLower().Replace(" ", "");

        if (modifiedInput == "optiona")
        {

        }
        else if (modifiedInput == "optionb")
        {

        }
        else
        {

        }
    }

【问题讨论】:

  • Method2 中,您“保存”了一个对userInput.ToLower().Replace(" ", ""); 的调用。这并没有什么区别。

标签: c# performance variables memory-management


【解决方案1】:

总的来说,我更喜欢method2,因为它消除了一遍又一遍地重复操作的必要性。

但最终它是一个微优化。由于操作创建了一个新字符串,您可能会发现method2 稍微好一些。

但最后,如果你想找出 2 匹马中哪匹最快,那就去比赛吧。

【讨论】:

    【解决方案2】:

    如果用户输入的是“optionb”,那么method2会更好,如果用户输入的是“optiona”超过平均值,那么method1和method2将没有可识别的区别。

    【讨论】:

      【解决方案3】:

      我也更喜欢方法 2。但不是因为@David 提到的性能原因。

      方法 2 更容易阅读。

      使用临时变量会在方法中添加额外的一行。这条额外的行反映了您的方法中实际发生的额外操作步骤。

      特别是当你给这个变量一个有意义的名字“modifiedInput”时,其他程序员会更容易理解你的方法在做什么。

      更容易理解的代码意味着更好的可维护性。

      【讨论】:

        猜你喜欢
        • 2014-05-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-02
        • 2017-11-13
        • 2021-11-20
        • 2016-04-17
        • 1970-01-01
        相关资源
        最近更新 更多