Is there a performance difference when asking for conditions with boolean type variable or int type variable in java if statement?

Asked 2 years ago, Updated 2 years ago, 88 views

Is there a difference between asking 1byte boolean variable and 4byte int type variable when asking if??

To write it down briefly, it is as follows

boolean infiniteMode;

int gameScore;

[1]

if(infiniteMode)

{

//Infinite Mode Logic

}

else

{

//normal mode logic

}

[2]

if(gameScore >= 55)

{

//Infinite Mode Logic

}

else

{

//normal mode logic

}

[1][2] Logic with the same meaning.

It's already [2], but I need to improve the performance...

[2]->[1] I'm thinking about it.

I'd appreciate it if you could tell me if this is a lie or not.

java if문

2022-09-22 11:35

1 Answers

Boolean is also stored as int on jvm (save as 4 bytes in stack frame)

So boolean is zero or one in int.

There is no mnemonic (command) for boolean comparison even in byte code.

Of course... the method chicature is divided into I and Z, but it looks like the same byte code will come out within the method (oracle JVM only (up to at least 8 versions), but as far as I know, IBM JVM is the same.)

The JVM implementation is entirely vendor responsibility, so reading the specifications is a surefire way.

In summary, in JVM, boolean is treated as 4 bytes. So the comparison in if is the same as boolean or int.

boolean isFlag = true;
if(isFlag)
...
...
int isFlag = 1;
if(isFlag > 0)

The two above are the same. (Of course, method signatures are different.)

But if the question is greater than or equal to 54...is added as a regional variable because it has been entered. In other words, a byte code longer than the boolean processing code must be processed.

In this case, the boolean generates a shorter byte code. You only need to use ifne, which is a command that is not zero.


2022-09-22 11:35

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.