How to compare Boolean?

后端 未结 7 1451
太阳男子
太阳男子 2021-01-01 09:39

Take this for example (excerpt from Java regex checker not working):

while(!checker) {
    matcher = pattern.matcher(number);
    if(matcher.find())
                 


        
相关标签:
7条回答
  • 2021-01-01 10:19

    Regarding the performance of the direct operations and the method .equals(). The .equals() methods seems to be roughly 4 times slower than ==.

    I ran the following tests..

    For the performance of ==:

    public class BooleanPerfCheck {
    
        public static void main(String[] args) {
            long frameStart;
            long elapsedTime;
    
            boolean heyderr = false;
    
            frameStart = System.currentTimeMillis();
    
            for (int i = 0; i < 999999999; i++) {
                if (heyderr == false) {
                }
            }
    
            elapsedTime = System.currentTimeMillis() - frameStart;
            System.out.println(elapsedTime);
        }
    }
    

    and for the performance of .equals():

    public class BooleanPerfCheck {
    
        public static void main(String[] args) {
            long frameStart;
            long elapsedTime;
    
            Boolean heyderr = false;
    
            frameStart = System.currentTimeMillis();
    
            for (int i = 0; i < 999999999; i++) {
                if (heyderr.equals(false)) {
                }
            }
    
            elapsedTime = System.currentTimeMillis() - frameStart;
            System.out.println(elapsedTime);
        }
    }
    

    Total system time for == was 1

    Total system time for .equals() varied from 3 - 5

    Thus, it is safe to say that .equals() hinders performance and that == is better to use in most cases to compare Boolean.

    0 讨论(0)
提交回复
热议问题