note 128780 added to language.oop5.object-comparison
| From: | alexandre dot leborgne dot 83 at gmail dot com | Date: | Fri, 04 Aug 2023 13:41:36 +0000 |
| Subject: | note 128780 added to language.oop5.object-comparison | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-220740@lists.php.net to get a copy of this message | ||
To compare two objects:
Solution 1
<?php
$a === $a2;
?>
Solution 2
<?php
spl_object_id($a) === spl_object_id($b);
?>
Solution 1 is 20 times faster to compare when the probability of comparing 2 identical objects is
high
Solution 2 is 20 times faster to compare when the probability of comparing 2 different objects is
high
Code for benchmark :
<?php
class A{
public $a;
}
$a = new A();
// $a2 = new A(); // Solution 1 is faster
$s= microtime(true);
for($i = 0; $i < 10000; ++$i) {
// $a2 = new A(); // Solution 2 is faster
$a === $a2;
}
$e= microtime(true);
var_dump('1:'.($e - $s ) *1000);
$s= microtime(true);
for($i = 0; $i < 1000; ++$i) {
// $a2 = new A(); // Solution 2 is faster
spl_object_id($a) === spl_object_id($a2);
}
$e= microtime(true);
var_dump('2:' .($e - $s ) *1000);
?>
----
Server IP: 45.112.84.4
Probable Submitter: 45.91.157.134 (proxied: 109.190.87.86)
----
Manual Page -- https://php.net/manual/en/language.oop5.object-comparison.php
Edit -- https://main.php.net/note/edit/128780
Del: integrated -- https://main.php.net/note/delete/128780/integrated
Del: useless -- https://main.php.net/note/delete/128780/useless
Del: bad code -- https://main.php.net/note/delete/128780/bad+code
Del: spam -- https://main.php.net/note/delete/128780/spam
Del: non-english -- https://main.php.net/note/delete/128780/non-english
Del: in docs -- https://main.php.net/note/delete/128780/in+docs
Del: other reasons-- https://main.php.net/note/delete/128780
Reject -- https://main.php.net/note/reject/128780
Search -- https://main.php.net/manage/user-notes.php