Using resources as array indexes in PHP -
i using following method of hashing resource
s lookups:
$foo = socket_create(...); $bar = socket_create(...); $map[(int)$foo] = 'foo'; $map[(int)$bar] = 'bar'; echo $map[(int)$foo]; // "foo"
is integer
casting best option this? if not, other hashing method better or more efficient? these lookups performed in collection hundreds, many times per second in tight loop (socket polling), i've ruled out iteration-based solutions.
edit:
to explain situation little better, socket_select()
function takes arrays of socket resources reference , modifies them such after function call, contain resources have changed (e.g. ready read from). use socket
class wrapper socket resources, make code more abstract , testable:
$socketobject = new socket($socketresource);
another of classes keeps list of socket resources need polled every time call socket_select()
:
$reads = [$socketresource1, $socketresource2, ...]; socket_select($reads, null, null, 0);
after call socket_select()
, know socket resources have changed, meaningful in code, need know socket objects resources correspond to. thus, need way map socket resources objects:
foreach ($reads $socketresource) { // socket object $socketresource correspond here? // currently, use solution this: $socketobject = $this->map[(int)$socketresource]; // unfortunately, behavior isn't guaranteed, isn't reliable... }
the observed behavior when casting resources integer undefined (see caution note on bottom of page). if works , reliably did long time, have aware it's nothing can rely on not change without notice.
edit after clarifications:
instead of putting resource key, use 2 arrays. 1 mapping hashes of socket objects actual objects. , mapping same hashes resource. pass latter array socket_select
. under premise function not change array keys, can iterate array , use key socket in o(1):
$r1 = socket_create(af_inet, sock_stream, sol_tcp); $r2 = socket_create(af_inet, sock_stream, sol_tcp); $s1 = new socket($foo); $s2 = new socket($bar); $socketmap = array( spl_object_hash($s1) => $s1, spl_object_hash($s2) => $s2 ); $reads = array( spl_object_hash($s1) => $r1, spl_object_hash($s2) => $r2 ); socket_select($reads, null, null, 0); foreach (array_keys($reads) $hash) { $socketobject = $socketmap[$hash]; }
Comments
Post a Comment