Using the conditional/ternary operator:
freeCache = (freeCache > (2880 * 3)) ? (2880 * 3) : freeCache;
there is a value assignment in every case.
Using this normal if-Statement:
if(this.freeCache > (2880 * 3)) this.freeCache = (2880 * 3)
there should only be a value assignment if the freeCache value is too high.
So which of those is actually more performant?
Just for the fun of it, I tried compiling the two suggested implementations (ternary operator vs the explicit if statement). They both use if_icmple
instruction so I guess performance will be identical:
The if
version:
public static void main(java.lang.String[]);
Code:
0: iconst_0
1: istore_1
2: iload_1
3: sipush 8640
6: if_icmple 13
9: sipush 8640
12: istore_1
13: return
Using '?' ternary operator:
public static void main(java.lang.String[]);
Code:
0: iconst_0
1: istore_1
2: iload_1
3: sipush 8640
6: if_icmple 15
9: sipush 8640
12: goto 16
15: iload_1
16: istore_1
17: return
There's a slight inefficiency in using the ?
operator (At least in this specific case) due to the :
clause (the instructions labeled 15 and 16 in the above listing). The JVM will probably optimize away these redundant operations.
They're not even equivalent .
The ternary expression can be expanded to this:
if(freeCache > (2880 * 3)) {
freeCache = 2880 * 3;
} else {
freeCache = freeCache;
}
If you're really concerned about performance, there's a[n insignificant] performance hit in that you're performing a redundant assignment again.
In all cases you should strive for readability first . The single if
statement is likely a better choice, as that's more readable than the convoluted ternary expression you have.
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.