【发布时间】: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