본문 바로가기
Language/자바

자바 if else 와 swtich case 를 비교해보았다..

by 띵커베르 2023. 2. 11.
728x90
  • 선 결론: 유의미한 차이를 느끼지 못했고, 가독성과 스타일에 따라 그때그때 다르다.요즘 컴파일러가 알아서 잘 해주기 때문에 성능보다는 가독성으로 잘 정리하면 되지않을까..!? (물론 자체 테스트기 떄문에, 틀릴 수 있음)
  • 요즘 컴파일러 최적화가 잘되어있는지, 생각보다 차이가 날거라 생각했는데, 테스트코드를 잘못 만든것인가...좀 차이를 볼려고 횟수를 상당히 많이 늘리지않는이상은 유의미한 차이를 못느끼겠다.
  • jdk7 버전부터 String 비교가 가능한 것으로 알고있었는데, 이는 String 클래스에서 hasCode 를 오버라이딩 하여 컴파일러가 컴파일 할때 해당 hasCode를 순서대로 처리하는것으로 알고있어서 String 으로 비교, 숫자로 비교해도 차이가 날까 궁금했는데,
  • 이는 생각해보니 컴파일러가 최초 컴파일할때 숫자 순으로 코드를 재조립하기때문에 같을 것 같았다.
  • 자세한 테스트는 보지못했지만, if else if else 의 경우 마지막에 else 처리가 있나 없나에 따라 성능차이도 궁금했고, switch 문에서 default 가 있고 없고 차이도 궁금했지만, 조금 하다보니 의미가 없는 수준인거 같아서. 코드만 올리고 정리해야겠다..
  • 여튼 궁금증은 해결..
import java.util.Random;

public class PerformanceComparison {
    private static final int ITERATION_COUNT = 10000000;

    public static void main(String[] args) {
        long startTimeIfElse = System.currentTimeMillis();
        for (int i = 0; i < ITERATION_COUNT; i++) {
            MonthCheckerWithIfElse();
            resultProcess(0);
        }
        long endTimeIfElse = System.currentTimeMillis();
        System.out.println("If-else execution time: " + (endTimeIfElse - startTimeIfElse) + " milliseconds");

        long startTimeSwitch = System.currentTimeMillis();
        for (int i = 0; i < ITERATION_COUNT; i++) {
            MonthCheckerWithSwitchCase();
            resultProcess(0);
        }
        long endTimeSwitch = System.currentTimeMillis();
        System.out.println("Switch execution time: " + (endTimeSwitch - startTimeSwitch) + " milliseconds");

        long startTimeSwitchMonthString = System.currentTimeMillis();
        for (int i = 0; i < ITERATION_COUNT; i++) {
            MonthCheckerWithSwitchCaseInOrder();
            resultProcess(0);
        }
        long endTimeSwitchMonthString = System.currentTimeMillis();
        System.out.println("endTimeSwitchMonthString time: " + (endTimeSwitch - startTimeSwitch) + " milliseconds");
    }

    private static void resultProcess(int result) {
        int x = result * result;
    }

    public static void MonthCheckerWithIfElse() {
        Random rand = new Random();
        int randomMonth = rand.nextInt(13) + 1;
        int month = -1;
        if (randomMonth == 1) {
            month = 1;
        } else if (randomMonth == 2) {
            month = 2;
        } else if (randomMonth == 3) {
            month = 3;
        } else if (randomMonth == 4) {
            month = 4;
        } else if (randomMonth == 5) {
            month = 5;
        } else if (randomMonth == 6) {
            month = 6;
        } else if (randomMonth == 7) {
            month = 7;
        } else if (randomMonth == 8) {
            month = 8;
        } else if (randomMonth == 9) {
            month = 9;
        } else if (randomMonth == 10) {
            month = 10;
        } else if (randomMonth == 11) {
            month = 11;
        } else if (randomMonth == 12) {
            month = 12;
        } else {
            month = 99;
        }
    }

    public static void MonthCheckerWithSwitchCase() {
        Random rand = new Random();
        int randomMonth = rand.nextInt(13) + 1;
        int month = -1;
        switch (randomMonth) {
            case 1:
                month = 1;
                break;
            case 2:
                month = 2;
                break;
            case 3:
                month = 3;
                break;
            case 4:
                month = 4;
                break;
            case 5:
                month = 5;
                break;
            case 6:
                month = 6;
                break;
            case 7:
                month = 7;
                break;
            case 8:
                month = 8;
                break;
            case 9:
                month = 9;
                break;
            case 10:
                month = 10;
                break;
            case 11:
                month = 11;
                break;
            case 12:
                month = 12;
                break;
            default:
                month = 99;
                break;
        }
    }

    private static void MonthCheckerWithSwitchCaseInOrder() {
        String[] months = {"January", "February", "March", "April", "May", "June",
                "July", "August", "September", "October", "November", "December"};

        Random rand = new Random();
        int randomIndex = rand.nextInt(months.length);
        String randomMonth = months[randomIndex];

        int month = -1;
        switch (randomMonth) {
            case "January":
                month = 1;
                break;
            case "February":
                month = 2;
                break;
            case "March":
                month = 3;
                break;
            case "April":
                month = 4;
                break;
            case "May":
                month = 5;
                break;
            case "June":
                month = 6;
                break;
            case "July":
                month = 7;
                break;
            case "August":
                month = 8;
                break;
            case "September":
                month = 9;
                break;
            case "October":
                month = 10;
                break;
            case "November":
                month = 11;
                break;
            case "December":
                month = 12;
                break;
        }
    }
}
728x90

'Language > 자바' 카테고리의 다른 글

JVM G1 GC 방식에 대해..  (0) 2023.02.12
자바 가비지 콜렉터(GC)에 대한 정리.  (0) 2023.02.12
자바 람다 Supplier example  (0) 2023.02.02
자바 접근지시자  (0) 2023.01.29
자바 오토박싱 & 언박싱  (0) 2023.01.29

댓글