티스토리 뷰

반응형

1. true || false 인 경우

@SpringBootTest
public class SimpleTest {

    @Autowired
    OrganizationRepository organizationRepository;

    @Test
    void test_true가_먼저_있을_때(){
        long start = System.currentTimeMillis();
        int size= 20;
        Random random = new Random();
        for (int i = 0; i < 10000; i++) {
            long id = (long)random.nextInt(size);
            if (sleepTrue(id) || sleepFalse(id)){
                continue;
            }
        }
        long end = System.currentTimeMillis();
        System.out.println("*********************");
        System.out.println((end-start)/1000.0);
        System.out.println("*********************");
    }

    public boolean sleepTrue(long id){
        organizationRepository.findById(id);
        return true;
    }

    public boolean sleepFalse(long id){
        organizationRepository.findById(id);
        return false;
    }
}

우선 기본 자바로 테스트 할려고 했는데 제가 생각한대로 나오질 않아서 junit을 통해 테스트를 진행하게 되었다.

위를 테스트를 했을 때 다음과 같은 결과가 나왔다.

 

 

대략 2초 정도의 결과가 나왔다.

 

2. false || true 인 경우

@SpringBootTest
public class SimpleTest {

    @Autowired
    OrganizationRepository organizationRepository;

    @Test
    void test_false가_먼저_있을_때(){
        long start = System.currentTimeMillis();
        int size= 20;
        Random random = new Random();
        for (int i = 0; i < 10000; i++) {
            long id = (long)random.nextInt(size);
            if (sleepFalse(id) || sleepTrue(id)){
                continue;
            }
        }
        long end = System.currentTimeMillis();
        System.out.println("*********************");
        System.out.println((end-start)/1000.0);
        System.out.println("*********************");
    }

    public boolean sleepTrue(long id){
        organizationRepository.findById(id);
        return true;
    }

    public boolean sleepFalse(long id){
        organizationRepository.findById(id);
        return false;
    }
}

 

이렇게 차이가 나는 이유는 or 연산자의 경우에는 첫 번째가 true이면 거기서 멈추지만 false 인 경우에는 그 다음 값을 비교하게 된다.

그러므로  ' ||' 을 쓸 때에는 되도록 true일 확률이 높은 것을 앞에 두면 좋을 것 같다. 이렇게 미세하지만 성능을 향상시킬 수 있다는 것을 알아두자.

반응형
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/08   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함