-2

Which has a larger bytecode size or the same in Java?

if (a > b) a = b;

vs

if (a > b) {
    a = b;
}
webelf000
  • 147
  • 9
  • See for yourself: https://stackoverflow.com/questions/3315938/is-it-possible-to-view-bytecode-of-class-file – dnault Nov 06 '20 at 06:19

1 Answers1

5

These compile to precisely the same thing.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
  • Thank you. c = a > b ? a: b; if (a > b) c = a; else c = b; Do they also turn into the same byte code? – webelf000 Nov 06 '20 at 03:41
  • 2
    Probably not the same bytecode. Almost certainly exactly the same performance. – Louis Wasserman Nov 06 '20 at 03:43
  • 2
    @webelf000 You can find out for yourself by running `javap -c path/to/MyClass.class` – dnault Nov 06 '20 at 06:18
  • 2
    @webelf000 https://ideone.com/sCGcit – Holger Nov 06 '20 at 08:54
  • Thanks, it looks ?: operator is faster and less size than if clause. – webelf000 Nov 06 '20 at 18:07
  • 1
    Like I said, "less size" and "faster" are not the same thing. Bytecode size is virtually meaningless as a measure of performance. – Louis Wasserman Nov 06 '20 at 18:18
  • 1
    @webelf000 the method size does not say anything about performance. Most environments have an optimizing Just-In-Time compiler which eliminates such differences anyway. But even if we assume the simplest interpreter, executing these instructions as-is, the *executed instructions* do not differ. Pick either scenario, `a > b` or `a <= b` and go step by step through the code, to check which instructions are actually executed. You’ll see that for each variant, the same instructions are executed, with only one tiny difference in the order, `istore_2, goto` vs `goto, istore_2`. Always the same work… – Holger Nov 09 '20 at 08:55