Why is casting and comparing in PHP faster than is_*?
Posted
by tstenner
on Stack Overflow
See other posts from Stack Overflow
or by tstenner
Published on 2010-06-05T20:34:10Z
Indexed on
2010/06/05
20:52 UTC
Read the original article
Hit count: 121
While optimizing a function in PHP, I changed
if(is_array($obj)) foreach($obj as $key=>$value { [snip] }
else if(is_object($obj)) foreach($obj as $key=>$value { [snip] }
to
if($obj == (array) $obj) foreach($obj as $key=>$value { [snip] }
else if($obj == (obj) $obj) foreach($obj as $key=>$value { [snip] }
After learning about ===
, I changed that to
if($obj === (array) $obj) foreach($obj as $key=>$value { [snip] }
else if($obj === (obj) $obj) foreach($obj as $key=>$value { [snip] }
Changing each test from is_* to casting resulted in a major speedup (>30%).
I understand that ===
is faster than ==
as no coercion has to be done, but why is casting the variable so much faster than calling any of the is_*-functions?
© Stack Overflow or respective owner