PHP isset() performance

Since I had done some PHP benchmarking last week, I wondered about the performance implications of a technique that I use sometimes. Consider the following examples:

// example 1
if (isset($_SESSION['var1'])) {
  $var1 = mysql_real_escape_string($_SESSION['var1']);
} else {
  $var1 = "";
}

// example 2
$var1 = mysql_real_escape_string(@$_SESSION['var1']);

Example 1 is much more verbose than example 2. Based on syntax alone I would always choose example 2. However, up until now I've never considered whether there are performance problems with using @. Although the notice does not interfere with the program, it is possible that it has a bad influence on performance.

Test Setup

I had to run the following tests 1-million times to even reach an order of magnitude that matters -- that alone says that this isn't a BIG issue, but let's continue. Here are the two tests I wrote, each run 1,000,000 times.

// test 1: using a condition to avoid array-out-of-bounds notice
if (isset($_SESSION['something_that_doesnt_exist']) )
  $a = $_SESSION['something_that_doesnt_exist'];

// test 2: hiding error message and acting cool.
$a = @$_SESSION['something_that_doesnt_exist'];

Results

Test 1: Total time: 0.12 seconds
Test 2: Total time: 1.04 seconds

Hiding error messages is 11 times slower than using an if-statement to avoid the error-prone code. There it is. If you have an loop that runs 99% of your application and ALL IT DOES is use @ then you may want to write that if-statement, but for the rest of us humans, we don't really bat an eye at the handful of places where 0.0000014 seconds are added to a page-load.

Still, I'm glad to know the impact!

Related Posts