c# - Create variable or call method few times - What's better? -


im wondering creating new variable or calling method few times. better overall performance , gc cleaning? take 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 make code clear?

in general, when need use result of method call multiple times, should assign local variable first. local variable require method's stack frame few bytes larger (8 bytes object variable on 64-bit), , cleared automatically when method returns – has no effect on gc.

the repeated method invocation, on other hand, require logic executed again, incurring allocation of required stack frames , possibly instantiation of objects. in case, registrykey.getvalue makes situation worse, since needs access windows registry, making several orders of magnitude slower local variable access. additionally, face race conditions 2 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 issue largely redressed in c# 6, can use 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(); } 

Comments

Popular posts from this blog

shopping cart - Page redirect not working PHP -

php - How to modify a menu to show sub-menus -

python - Installing PyDev in eclipse is failed -