简体   繁体   English

在if-else中调用方法或在if-else中调用方法

[英]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. 我有一个关于在if-else或if-else语句之外调用方法的问题。

Calling method in if-else : 调用方法 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 : 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 如果条件仅执行一次,它将不会对您的性能产​​生重大影响

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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