Which “if” construct is faster - statement or ternary operator?

前端 未结 6 681
借酒劲吻你
借酒劲吻你 2020-12-01 01:08

There are two types of if statements in java - classic: if {} else {} and shorthand: exp ? value1 : value2. Is one faster than the oth

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-01 01:49

    Both of your examples will probably compile to identical or nearly identical bytecode, so there should be no difference in performance.

    Had there been a difference in execution speed, you should still use the most idiomatic version (which would be the second one for assigning a single variable based on a simple condition and two simple sub-expressions, and the first one for doing more complex operations or operations that do not fit on a single line).

提交回复
热议问题