There are a lot of places in code which seems like:
public function getSomeFilteredThings(Someobj $obj = null, Someobj2 $obj2 = null)
It's restrict type by php typehint and we can don't care about type of variable but task of checking is null or object passed still available.
Most common methods to check are: if ($obj)
, if (null === $obj)
and if ($obj instanceof Someobj)
.
All tests executes in php5 cli interface on my old notebook (intel t7200).
$ php -v
PHP 5.6.15-1 (cli)
Copyright (c) 1997-2015 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2015 Zend Technologies
with Zend OPcache v7.0.6-dev, Copyright (c) 1999-2015, by Zend Technologies
Class a {};
$a = new a;
To reduce a mathematical error testcases executed 10M times:
$start = microtime(1);for ($i=0;$i<10000000;$i++) {if (null === $a) {}} echo (microtime(1) - $start)*1000;
All testcase executes 5 times and results approximated. Spread is about ±5ms, which prove that tests are stable can be representative.
Result:
Condition | Result, ms |
---|---|
null === $a | 625 |
null !== $a | 705 |
$a | 705 |
$a instanceof a | 840 |
I doubted what method is the most fast — (null === $obj)
or ($obj)
. Now it's clear :) Difference between it is about 15%, but keep in mind that it's opposite condition, while same condition is equal. Instanceof
is quite slow and it's very not good because it's most straightforward testing of variable. I was sure that instanceof
will be slowest on php <7. Lets look results on 3v4l.org: https://3v4l.org/MtEUI — spread probably is quite big but instanceof
is a winner ;) Yeah, we must throw away php5 and replace it with php7.