Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

isset($var) vs. @$var

Is this an okay practice or an acceptable way to use PHP's error suppressing?

if (isset($_REQUEST['id']) && $_REQUEST['id'] == 6) {
  echo 'hi';
}

if (@$_REQUEST['id'] == 6) {
  echo 'hi';
}

EDIT:
I thought so too. The code (and idea) is from friend.
Thanks for proving me right. :)

like image 382
johankj Avatar asked Apr 08 '10 13:04

johankj


1 Answers

Apart from being not a good practice, since @ can chew on really important errors down the call stack, performance penalty is minuscule.

Let's verify this with a benchmark.

<?php
error_reporting(-1);

$limit = 10000;

$start = microtime(true);
for ($i = 0; $i < 10000; $i++) {
    echo !isset($_GET['aaa']) ? '' : $_GET['aaa'];
}
$total = 1000000 * (microtime(true) - $start)/$limit;
echo "With isset: $total μs\n";

$start = microtime(true);
for ($i = 0; $i < 10000; $i++) {
    echo @$_GET['aaa'];
}
$total = 1000000 * (microtime(true) - $start)/$limit;
echo "With @: $total μs\n";

On my not-so-recent computer it outputs:

With isset: 0.295 μs
With @: 0.657 μs

μs is a millionth of a second. Both methods take close to half of a millionth of a second.

One could say, but what if I do this for hundreds or thousands times, will there will be any difference? If you have to do !isset() a million of times, then your program already spent about 0.3 second doing this! Which means that you shouldn't have been doing that in the first place.

Nevertheless, @ is a bad practice for anything more complex than a simple array, hence do not use it even if you know that performance difference is insignificant.

like image 148
sanmai Avatar answered Oct 07 '22 19:10

sanmai