简体   繁体   English

创建新的变量C#

[英]create new variable c#

Let say I want to use 假设我要使用

str.Split[' '].ElementAt(0) 10 times in my method.

Should I create a string variable called strSplit or just keep using str.Split[' '].ElementAt(0)? 我应该创建一个名为strSplit的字符串变量还是只继续使用str.Split [''] .ElementAt(0)? Is there a performance issue? 是否存在性能问题?

Use the entire returned array, not just the first element each time (unless you really only want the first element, and none of the others): 使用整个返回的数组,而不是每次都使用第一个元素(除非您真的只想要第一个元素,而其他都不想要):

var result = str.Split(" ");

foreach (var splitValue in result)
{
    // do something with splitValue
}

Memory is cheap. 内存很便宜。 Really cheap. 便宜。

So are CPU cycles. CPU周期也是如此。

Your current method will consume less memory (more while each call to Split has not been GC'd, but you don't store the result) by a tiny amount. 您当前的方法会消耗较少的内存(更多,而每次调用Split一直没有GC'd,但你没有保存的结果)按微小的量。 It will consume far more CPU cycles though, especially because the GC has to collect all the temp variables created by Split . 但是,这将消耗更多的CPU周期,尤其是因为GC必须收集Split创建的所有临时变量。 In reality, its not going to matter. 实际上,这无关紧要。 You won't see the performance difference. 您不会看到性能差异。

For good practice, store it off in a variable. 为了好的做法,请将其存储在变量中。 The memory used will be inconsequential, and your code will be much cleaner and more efficient (even if you don't see it!) 使用的内存将无关紧要,并且您的代码将更加整洁和高效(即使您没有看到它!)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM