Ignoring Errors For the Good?

In PHP the @ operator temporarily sets the error reporting level to 0 for one expression.  You will find it in many PHP scripts preceding mysql_connect often in combination with die to terminate the script with a custom error message.

@mysql_connect( $dbhost, $dbuser, $dbpassword) or die (‘Error establishing a database connection’);

Recently I found this line in the source code of Magento:

if(@$array[$key_that_might_exist])

Basically it looks like a more convenient way to check if the key exists and evaluates as true.

if(isset($array[key])) {
if($array[key]) {
// do something
}
}

// or, in one line

if(isset($array[key]) && $array[key]) {
// do something
}

While checking the PHP documentation I found one comment stating that the @ is pretty slow.

Be aware that using @ is dog-slow, as PHP incurs overhead to suppressing errors in this way. It’s a trade-off between speed and convenience.

I don’t believe what I don’t see, so I ran run a speed comparison test. This are the results:

// the time was measured with microtime(), each line has been iterated 100000 times.

// test array
$array = array('123' => 'test');

if(@$array['123']){}
// took 0.0344sec

if(isset($array['123']) && $array['123'] ){}
// took 0.0153sec

if(@$array['not']){}
// took 0.0730sec

if(isset($array['not']) && $array['not'] ){}
// took 0.0092sec

Conclusion

It is up to 8 times faster to  use isset() instead of the little more convenient @. The comment on php.net is right, it is everything but fast to use @ for this purpose.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>