简体   繁体   中英

calling method in if-else OR out of if-else

I have a question about calling a method in if-else or out of if-else statement.

Calling method in if-else :

int a = 1;

if (SOME_CONDITION) {
    /* Never chagned variable a */
    foo(a);
} else {
    /* Never chagned variable a */
    foo(a);
}

Calling method out of if-else :

int a = 1;

if (SOME_CONDITION) {
    /* Never chagned variable a */
} else {
    /* Never chagned variable a */
}

foo(a);

Which one has better performance?

There is no difference in the performance but in the code duplication. Thus the second way is better.

However, let me introduce you another way:

if (SOME_CONDITION) {
   /* Never chagned variable a */
 } else {
    /* Never chagned variable a */
}

int a = 1;
foo(a);

Or even better:

foo(1);

Keep the variable with the method that calls it if there are no steps between. Also, don't define a new variable since the value might be passed immediately.

Which one has better performance?

Either way, the method is only called once, so it won't make any difference.

In general, though, focus on writing clear, understandable, maintainable code, and worry about a performance problem if and when you have a specific performance problem to worry about.

In this case, your second option is clearer and more easily maintained (having the call in two places opens up the possibility of changing one of them and forgetting to change the other).

Performance wise, both are same.

Talking about memory, Second way is better. This method is known as code movement and is a code optimization technique. This is because if the function is made inline by compiler, then whole function body will be pasted twice which will lead to more code space. Hope that helps :)

两者具有相同的性能。

没有确定的差异,但是选项2是更好的代码,因为foo()不取决于条件

Programming itself suggests, one line is better than 2 lines. but in this case

if (SOME_CONDITION) {
/* Never chagned variable a */
foo(a);}

IT WILL HAVE NO SIGNIFICANT IMPACT IN YOUR PERFORMACE AS IF CONDITION EXECUTES JUST ONCE

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