简体   繁体   English

哪种方法会更有效? (Java Android编程)

[英]Which way will be more efficient ? (Java Android Programming)

In my app I need to change the value of an integer variable . 在我的应用程序中,我需要更改一个整数变量的值。 The way I have changed this , like this 我改变这种方式,像这样

  int variable; 

    if (condition) {
        variable= 1;                
    } 
    else if (condition) {
        variable= 2 ;               
    }
   ..........
   ..........
    else {
        variable=3;
    }

Or shpould I declare an array and change the value of variable like this 或者我应该声明一个数组并像这样更改变量的值

int variable; 

    if (condition) {
        variable= array[0];                
    } 
    else if (condition) {
        variable= array[1];               
    }
   ..........
   ..........
    else {
        variable=0;
    }

Which the more performance optimized way ? 哪种性能更优化的方式? Or both do the same ? 还是两者都一样?

如果梯形图的其他内容过多,则可以使用switch语句来更清楚和快速访问

If your values are constants and simple integers then the first choice is more preferable as that would avoid the overhead of creating arrays and thus saving some memory for you. 如果您的值是常量和简单整数,则首选第一选择,因为这样可以避免创建数组的开销,从而为您节省一些内存。 :) :)

Also, for switching between the conditions you can consider @henrycharles answer as switch case at times prove more efficient than if-else. 同样,对于条件之间的切换,您可以考虑@henrycharles答案,因为有时切换情况比if-else更有效。

The performance will slightly be worse in the second case I assume (but you will not notice it). 在我假设的第二种情况下,性能会稍差(但您不会注意到)。 I mean you have to bring additional variables to the stack - the array itself. 我的意思是,您必须将其他变量(数组本身)带到堆栈中。 You will need more memory as well to create and keep the array. 您还将需要更多内存来创建和保留阵列。

But because you have if/else branching, a missed if/else branch will have a bigger impact then array or not-array. 但是因为您具有if / else分支,所以错过的if / else分支将对数组或非数组产生更大的影响。 Either way I would not worry too much about it, this difference will be in the order of ns. 无论哪种方式,我都不会对此太担心,这种差异约为ns。

Of course you call always measure- but micro-benchmarking Java is not always easy. 当然,您总是称其为测量-但微基准测试Java并不总是那么容易。

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

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