개발/Code review

Java "Switch vs If which is better for String comparison"

iceblueberry 2020. 7. 31. 10:18

아래 링크 참고

https://stackoverflow.com/questions/41635131/gradle-getting-the-root-project-directory-path-when-starting-with-a-custom-buil#comment72687129_41635558

 

Gradle: getting the root project directory path when starting with a custom build file

The structure of my Gradle project is the following: Project ├── app └── build.gradle ├── foo └── bar.txt · · · └── build.gradle Normally to get the absolute path of the foo folder I ca...

stackoverflow.com

 

final static int FOO_HASHCODE = 70822; // "Foo".hashCode();
final static int BAR_HASHCODE = 66547; // "Bar".hashCode();

public static void main(String[] args) {
    String s = "Bar";
    switch (s.hashCode()) {
    case FOO_HASHCODE:
        if (s.equals("Foo"))
            System.out.println("Foo match");
        break;
    case BAR_HASHCODE:
        if (s.equals("Bar"))
            System.out.println("Bar match");
        break;
    }
}

위 코드는 Switch Statement으로 작성한 코드를 Decompile 했을 때 예상결과이다. 첫 비교 때 HashCode로 비교하기 때문에 훨씬 빠르다.

 

결론

Use Switch Statement to compair String for more than 2 cases.

'개발 > Code review' 카테고리의 다른 글

Early return  (0) 2020.07.31
Code Review: Return Empty Collections Instead of Null  (0) 2020.07.27