program story

삼항 연산자가 Java의 "if"조건보다 빠릅니까?

inputbox 2020. 8. 4. 07:19
반응형

삼항 연산자가 Java의 "if"조건보다 빠릅니까?


이 질문에는 이미 답변이 있습니다.

나는 " 조건부 증후군 "에 걸리기 쉬우므로 항상 조건을 사용하는 경향이 있습니다. 삼항 연산자는 거의 사용하지 않습니다. 예를 들어 :

//I like to do this:
int a;
if (i == 0)
{
    a = 10;
}
else
{
    a = 5;
}

//When I could do this:
int a = (i == 0) ? 10:5;

내가 사용하는 것이 중요합니까? 어느 것이 더 빠릅니까? 눈에 띄는 성능 차이가 있습니까? 가능하면 가장 짧은 코드를 사용하는 것이 더 좋은 방법입니까?


내가 사용하는 것이 중요합니까?

예! 두 번째는 훨씬 더 읽기 쉽습니다. 당신은 한 줄을 거래하여 9 줄의 효과적으로 혼란에 대해 원하는 것을 간결하게 표현합니다.

어느 것이 더 빠릅니까?

둘 다.

가능하면 가장 짧은 코드를 사용하는 것이 더 좋은 방법입니까?

“가능한 경우”는 아니지만 가능한 한 해로운 영향없이 가능합니다. 짧은 코드는 부수적 인 영향 ( "보일러 플레이트 코드")보다는 관련 부분에 초점을두기 때문에 잠재적으로 더 읽기 쉽습니다.


있다면 어떤 성능 차이를 (I 의심되는)은 무시할 수있을 것입니다. 가장 간단하고 읽기 쉬운 코드 작성에 집중하십시오.

말했듯이 조건부 연산자의 혐오감을 극복하려고 노력하십시오. 과도하게 사용하는 것이 가능하지만 어떤 경우에는 실제로 유용 할 수 있습니다 . 당신이 준 구체적인 예에서, 나는 분명히 조건 연산자를 사용할 것입니다.


삼항 연산자 예 :

int a = (i == 0) ? 10 : 5;

다음과 같이 if / else로 할당을 수행 할 수 없습니다.

// invalid:
int a = if (i == 0) 10; else 5;

이것은 삼항 연산자를 사용해야하는 좋은 이유입니다. 과제가없는 경우 :

(i == 0) ? foo () : bar ();

if / else가 훨씬 더 많은 코드가 아닙니다.

if (i == 0) foo (); else bar ();

성능이 중요한 경우 : 측정하십시오. 병목 현상이있는 경우 대상 머신, 대상 JVM을 사용하여 일반적인 데이터로 측정하십시오. 그렇지 않으면 가독성이 좋습니다.

문맥에 포함 된 짧은 형식은 때때로 매우 편리합니다.

System.out.println ("Good morning " + (p.female ? "Miss " : "Mister ") + p.getName ()); 

그렇습니다.하지만 코드 실행 성능 때문이 아닙니다.

빠른 (성능적인) 코딩은 간단한 구문 구성보다 루핑 및 객체 인스턴스화와 관련이 있습니다. 컴파일러는 최적화를 처리해야합니다 (모두 같은 바이너리 일 것입니다!). 목표는 You-From-The-Future의 효율성이어야합니다 (인간은 항상 소프트웨어의 병목 현상입니다).

Josh Bloch의 "성능 불안"이야기 Parleys.com

The answer citing 9 lines versus one can be misleading: less lines of code does not always equal better. Ternary operators can be a more concise way in limited situations (your example is a good one).

BUT they can often be abused to make code unreadable (which is a cardinal sin) = do not nest ternary operators!

Also consider future maintainability, if-else is much easier to extend or modify:

int a;
if ( i != 0 && k == 7 ){
    a = 10;
    logger.debug( "debug message here" );
}else
    a = 3;
    logger.debug( "other debug message here" );
}


int a = (i != 0 && k== 7 ) ? 10 : 3;  // density without logging nor ability to use breakpoints

p.s. very complete stackoverflow answer at To ternary or not to ternary?


Ternary operators are just shorthand. They compile into the equivalent if-else statement, meaning they will be exactly the same.


Also, the ternary operator enables a form of "optional" parameter. Java does not allow optional parameters in method signatures but the ternary operator enables you to easily inline a default choice when null is supplied for a parameter value.

For example:

public void myMethod(int par1, String optionalPar2) {

    String par2 = ((optionalPar2 == null) ? getDefaultString() : optionalPar2)
            .trim()
            .toUpperCase(getDefaultLocale());
}

In the above example, passing null as the String parameter value gets you a default string value instead of a NullPointerException. It's short and sweet and, I would say, very readable. Moreover, as has been pointed out, at the byte code level there's really no difference between the ternary operator and if-then-else. As in the above example, the decision on which to choose is based wholly on readability.

Moreover, this pattern enables you to make the String parameter truly optional (if it is deemed useful to do so) by overloading the method as follows:

public void myMethod(int par1) {
    return myMethod(par1, null);
}

For the example given, I prefer the ternary or condition operator (?) for a specific reason: I can clearly see that assigning a is not optional. With a simple example, it's not too hard to scan the if-else block to see that a is assigned in each clause, but imagine several assignments in each clause:

if (i == 0)
{
    a = 10;
    b = 6;
    c = 3;
}
else
{
    a = 5;
    b = 4;
    d = 1;
}

a = (i == 0) ? 10 : 5;
b = (i == 0) ? 6  : 4;
c = (i == 0) ? 3  : 9;
d = (i == 0) ? 12 : 1;

I prefer the latter so that you know you haven't missed an assignment.


It's best to use whatever one reads better - there's in all practical effect 0 difference between performance.

In this case I think the last statement reads better than the first if statement, but careful not to overuse the ternary operator - sometimes it can really make things a lot less clear.


Try to use switch case statement but normally it's not the performance bottleneck.

참고URL : https://stackoverflow.com/questions/9745389/is-the-ternary-operator-faster-than-an-if-condition-in-java

반응형