your programing

어떤 "if"구문이 더 빠른가요? 문 또는 삼항 연산자?

lovepro 2020. 10. 5. 20:31
반응형

어떤 "if"구문이 더 빠른가요? 문 또는 삼항 연산자?


두 가지 유형이 있습니다 if: 고전 - 자바의 문장 if {} else {}과 속기가 : exp ? value1 : value2. 하나가 다른 것보다 빠르거나 같습니까?

성명서:

int x;
if (expression) {
  x = 1;
} else {
  x = 2;
}

삼항 연산자 :

int x = (expression) ? 1 : 2;

거기에는 한 가지 유형의 "if"문만 있습니다. 다른 하나는 조건식입니다. 어느 쪽이 더 나은 성능을 낼 수 있는지 : 그들은 동일한 바이트 코드로 컴파일 할 수 있으며, 동일하게 작동 할 것으로 기대합니다. 또는 성능 측면에서 다른 하나를 선택하고 싶지 않을 정도로 가깝습니다.

때로는 if문이 더 읽기 쉽고 조건 연산자가 더 읽기 쉽습니다. 두 피연산자가 간단하고 부작용이없는 경우 두 가지의 주요 목적은 경우 반면 특히, 나는, 조건 연산자를 사용하는 것이 좋습니다 것 입니다 그들의 부작용, 내가 아마 사용하십시오 if문을.

다음은 샘플 프로그램과 바이트 코드입니다.

public class Test {
    public static void main(String[] args) {
        int x;
        if (args.length > 0) {
            x = 1;
        } else {
            x = 2;
        }
    }

    public static void main2(String[] args) {
        int x = (args.length > 0) ? 1 : 2;
    }
}

다음으로 디 컴파일 된 바이트 코드 javap -c Test:

public class Test extends java.lang.Object {
  public Test();
    Code:
       0: aload_0
       1: invokespecial #1
       4: return

  public static void main(java.lang.String[]
    Code:
       0: aload_0
       1: arraylength
       2: ifle          10
       5: iconst_1
       6: istore_1
       7: goto          12
      10: iconst_2
      11: istore_1
      12: return

  public static void main2(java.lang.String[
    Code:
       0: aload_0
       1: arraylength
       2: ifle          9
       5: iconst_1
       6: goto          10
       9: iconst_2
      10: istore_1
      11: return
}

보시다시피, 여기에서 바이트 코드에 약간의 차이 istore_1가 있습니다.-브랜 스 내 에서 발생 하든 그렇지 않든 (이전의 큰 결함이있는 시도와는 달리 :) JITter가 다른 네이티브 코드로 끝났다면 매우 놀랍습니다.


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).


These are the same. Both of them are fairly fast, typically around 10-30 nano-seconds. (depending on usage pattern) Is this time frame important to you?

You should do what you believe is clearest.


Just to add to all the other answers:

The second expression is often called tertiary/ternary operator/statement. It can be very useful because it returns an expression. Sometimes it makes the code more clearer for typical short statements.


neither - they will be compiled to the same.

참고URL : https://stackoverflow.com/questions/4706696/which-if-construct-is-faster-statement-or-ternary-operator

반응형