简体   繁体   中英

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? 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.

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. 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:

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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