note 98157 added to function.is-object
| From: | hperrinatgmaildotcom at osu1 dot php dot net | Date: | Fri, 28 May 2010 17:12:47 +0000 |
| Subject: | note 98157 added to function.is-object | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-169698@lists.php.net to get a copy of this message | ||
I've found a faster way of determining an object. If you use is_object() millions of times, you
will notice a *huge* difference. On my machine, this method takes about 1/4 the time of using
is_object().
Cast the value to an object, then check (using ===) if it is identical to the original.
<?php
if ( (object) $unknown === $unknown ) {
echo '$unknown is an object';
} else {
echo '$unknown is not an object';
}
?>
You can use this script to test the speed of both methods.
<pre>
What's faster for determining objects?
<?php
$count = 1000000;
$test = (object) array('i' => 'am', 'going' => 'to
be', 'an' => 'object');
$test2 = 'im not an object';
$test3 = array('im', 'not', 'an', 'object');
$test4 = 42;
// Set this now so the first for loop doesn't do the extra work.
$i = $start_time = $end_time = 0;
$start_time = microtime(true);
for ($i = 0; $i < $count; $i++) {
if (!is_object($test) || is_object($test2) || is_object($test3) || is_object($test4)) {
echo 'error';
break;
}
}
$end_time = microtime(true);
echo 'is_object : '.($end_time - $start_time)."\n";
$start_time = microtime(true);
for ($i = 0; $i < $count; $i++) {
if (!(object) $test === $test || (object) $test2 === $test2 || (object) $test3 === $test3 ||
(object) $test4 === $test4) {
echo 'error';
break;
}
}
$end_time = microtime(true);
echo 'cast, === : '.($end_time - $start_time)."\n";
echo "\nTested $count iterations."
?>
</pre>
Prints something like:
What's faster for determining objects?
is_object : 8.2549629211426
cast, === : 2.1297039985657
Tested 1000000 iterations.
----
Server IP: 69.147.83.197
Probable Submitter: 65.44.194.66
----
Manual Page -- http://www.php.net/manual/en/function.is-object.php
Edit -- https://master.php.net/note/edit/98157
Del: integrated -- https://master.php.net/note/delete/98157/integrated
Del: useless -- https://master.php.net/note/delete/98157/useless
Del: bad code -- https://master.php.net/note/delete/98157/bad+code
Del: spam -- https://master.php.net/note/delete/98157/spam
Del: non-english -- https://master.php.net/note/delete/98157/non-english
Del: in docs -- https://master.php.net/note/delete/98157/in+docs
Del: other reasons-- https://master.php.net/note/delete/98157
Reject -- https://master.php.net/note/reject/98157
Search -- https://master.php.net/manage/user-notes.php