[英]Create variable or call method few times - What's better?
Im wondering about creating new variable or calling method few times. 我想知道几次创建新的变量或调用方法。 What is better for overall performance and GC cleaning? 整体性能和GC清洁有什么好处? Take a look: 看一看:
public static string GetValue(RegistryKey key, string value)
{
if (key.GetValue(value) == null)
return null;
string newValue = key.GetValue(value).ToString();
if (String.IsNullOrWhiteSpace(newValue))
return null;
return newValue.ToLower();
}
How can I make this code clear? 如何清除此代码?
In general, when you need to use the result of a method call multiple times, you should assign it to a local variable first. 通常,当您需要多次使用方法调用的结果时,应首先将其分配给局部变量。 The local variable would only require your method's stack frame to be a few bytes larger (8 bytes for an object variable on 64-bit), and would get cleared automatically when the method returns – it has no effect on the GC. 局部变量只需要你的方法的堆栈帧大几个字节(对于64位的对象变量为8个字节),并且在方法返回时会自动清除 - 它对GC没有影响。
The repeated method invocation, on the other hand, would require all its logic to be executed again, incurring the allocation of the required stack frames and possibly instantiation of objects. 另一方面,重复的方法调用将需要再次执行其所有逻辑,从而导致所需堆栈帧的分配以及可能的对象实例化。 In your case, RegistryKey.GetValue
makes the situation even worse, since it needs to access the Windows Registry, making it several orders of magnitude slower than the local variable access. 在您的情况下, RegistryKey.GetValue
使情况更糟,因为它需要访问Windows注册表,使其比本地变量访问慢几个数量级。 Additionally, you could face race conditions where the two calls return different values. 此外,您可能面临两种调用返回不同值的竞争条件。
public static string GetValue(RegistryKey key, string name)
{
object value = key.GetValue(name);
if (value == null)
return null;
string valueStr = value.ToString()
if (String.IsNullOrWhiteSpace(valueStr))
return null;
return valueStr.ToLower();
}
Note that this issue will be largely redressed in C# 6, where you can use the null-conditional operator: 请注意,此问题将在C#6中得到很大程度的解决,您可以使用空条件运算符:
public static string GetValue(RegistryKey key, string name)
{
string value = key.GetValue(name)?.ToString();
if (String.IsNullOrWhiteSpace(value))
return null;
return value.ToLower();
}
Create a local variable and call the method once. 创建一个局部变量并调用该方法一次。 There is (admittedly small) overhead to local method calls. 本地方法调用(通常很小)开销。 If you were using a remote method call the difference would be much more pronounced. 如果您使用远程方法调用,差异将更加明显。
using ? 用? operator makes it more readable also better performance as u can see 如你所见,运算符使其更具可读性和更好的性能
public static string GetValue(RegistryKey key, string value)
{
string valueStr=(string)key.GetValue(value);
return string.IsNullOrWhiteSpace(valueStr)?null:valueStr.ToLower();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.