What is the difference between is_a and instanceof?

后端 未结 9 912
难免孤独
难免孤独 2020-12-04 07:23

I am aware that instanceof is an operator and that is_a is a method.

Is the method slower in performance? What would you prefer to use?

9条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-04 07:56

    Here are performance results obtained from here:

    instanceof is faster.

    Functions

    function method_1($a = null) { 
        return is_object($a) && is_a($a, 'Example');
    }
    
    function method_2($a = null) {
        return is_a((object) $a, 'Example');
    }
    
    function method_3($a = null) {
        return $a instanceof 'Example';
    }
    

    Times (run 5000 times each)

    0.00573397 // method_1(5) 
    0.01437402 // method_2(5) 
    0.00376201 // method_3(5)
    

提交回复
热议问题