On Fri, Nov 28, 2014 at 3:02 PM, Patrick Schaaf <p...@bof.de> wrote:

>  On Friday 28 November 2014 14:51:55 Ferenc Kovacs wrote:
>
> >
>
> > I also used spl_object_hash() in the past when traversing/custom
>
> > serializing object structures which can have infinite recursions between
>
> > objects, but even that could be simply solved by storing the already
>
> > traversed objects in an array (as assigning the objects into another
>
> > variable doesn't have much overhead) and checking with in_array.
>
>
>
> Checking with in_array is O(N) while an array keyed on spl_object_hash()
> with the values being the objects, is stable wrt. hash string vs. object
> lifetime, and is O(1) on checking for key existence.
>
>
>
> The performance difference will become apparent when you have more than a
> handful of objects there.
>

yeah, if you already have the hashmap ready, then
calling array_key_exists(spl_object_hash($needle), $haystack) will be much
cheaper.
but don't forget that for that you have to build the hashmap, eg. you have
to call spl_object_hash() for each element, so you can't ignore the cost of
that when comparing to the simple in_array solution.
from a quick test using spl_object_hash seems to be the slower with big
number of elements in haystack.

<?php
$iteration = (int)$argv[1];
$needle = new StdClass;
$haystack = array();
for ($i=0;$i<$iteration;$i++) {
    $haystack[] = new StdClass;
}
$haystack[] = $needle;
var_dump(in_array($needle, $haystack, true));

vs

<?php
$iteration = (int)$argv[1];
$needle = new StdClass;
$key = spl_object_hash($needle);
$haystack = array();
for ($i=0;$i<$iteration;$i++) {
    $object = new StdClass;
    $haystack[spl_object_hash($object)] = $object;
}
$haystack[$key] = $needle;
var_dump(array_key_exists($key, $haystack));




>
>
> BTW, the two or three places where I use spl_object_hash(), in this way,
> are exactly your use case: as an "already visited" cache during traversal
> of somewhat arbitrary input structure (logging / dumping).
>
>
>
>

thanks for the feedback!

-- 
Ferenc Kovács
@Tyr43l - http://tyrael.hu

Reply via email to