几次创建变量或调用方法 - 哪个更好?
Create variable or call method few times - What's better?
我想知道创建新变量或调用方法几次。
什么对整体性能和 GC 清洁更好?
看看:
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();
}
如何让这段代码清晰?
创建一个局部变量并调用该方法一次。本地方法调用有(不可否认的)开销。如果您使用远程方法调用,差异会更加明显。
一般来说,当你需要多次使用一个方法调用的结果时,应该先将其赋值给一个局部变量。局部变量只需要你的方法的堆栈帧大几个字节(64 位上的对象变量为 8 个字节),并且会在方法 returns 时自动清除——它对GC。
另一方面,重复的方法调用将需要再次执行其所有逻辑,从而导致分配所需的堆栈帧并可能实例化对象。在您的情况下, RegistryKey.GetValue
使情况变得更糟,因为它需要访问 Windows 注册表,使其比局部变量访问慢几个数量级。此外,您可能会遇到竞争条件,其中两个调用 return 不同的值。
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();
}
请注意,此问题将在 C# 6 中得到很大程度的解决,您可以在其中使用 null 条件运算符:
public static string GetValue(RegistryKey key, string name)
{
string value = key.GetValue(name)?.ToString();
if (String.IsNullOrWhiteSpace(value))
return null;
return value.ToLower();
}
使用?运算符使其更具可读性
如您所见,性能也更好
public static string GetValue(RegistryKey key, string value)
{
string valueStr=(string)key.GetValue(value);
return string.IsNullOrWhiteSpace(valueStr)?null:valueStr.ToLower();
}
我想知道创建新变量或调用方法几次。 什么对整体性能和 GC 清洁更好? 看看:
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();
}
如何让这段代码清晰?
创建一个局部变量并调用该方法一次。本地方法调用有(不可否认的)开销。如果您使用远程方法调用,差异会更加明显。
一般来说,当你需要多次使用一个方法调用的结果时,应该先将其赋值给一个局部变量。局部变量只需要你的方法的堆栈帧大几个字节(64 位上的对象变量为 8 个字节),并且会在方法 returns 时自动清除——它对GC。
另一方面,重复的方法调用将需要再次执行其所有逻辑,从而导致分配所需的堆栈帧并可能实例化对象。在您的情况下, RegistryKey.GetValue
使情况变得更糟,因为它需要访问 Windows 注册表,使其比局部变量访问慢几个数量级。此外,您可能会遇到竞争条件,其中两个调用 return 不同的值。
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();
}
请注意,此问题将在 C# 6 中得到很大程度的解决,您可以在其中使用 null 条件运算符:
public static string GetValue(RegistryKey key, string name)
{
string value = key.GetValue(name)?.ToString();
if (String.IsNullOrWhiteSpace(value))
return null;
return value.ToLower();
}
使用?运算符使其更具可读性 如您所见,性能也更好
public static string GetValue(RegistryKey key, string value)
{
string valueStr=(string)key.GetValue(value);
return string.IsNullOrWhiteSpace(valueStr)?null:valueStr.ToLower();
}