4

If I have code producing the above notice, and similar such as undefined offset for arrays, would adding isset() or empty() checks improve the performance of the script in addition to remvoing the error notices?

Edit: Just to clarify, I want error reporting on and I know isset will get around the notices, this question was more about the performance side.

bcmcfc
  • 25,966
  • 29
  • 109
  • 181

3 Answers3

5

First, I'm assuming you have 3 options.

The first is turning error_reporting off and using unknown array offsets with impunity:

error_reporting(0);

The second is using @ error suppression:

@$my_array['a'];

The third is using isset():

if (isset($my_array['a'])) {
    $my_array['a'];
}

I've hacked up a quick benchmarking script which gives the following results for 1000000 executions:

Turning off error reporting:  6 seconds
Using error suppression:     18 seconds
Using isset():                9 seconds
lonesomeday
  • 233,373
  • 50
  • 316
  • 318
  • It might be enough to turn off notices only (for example E_ALL & ~E_NOTICE for error_reporting). – kapa Nov 16 '10 at 11:49
  • @bazmegakapa True, although all errors should be turned off in production, for security and performance reasons. – lonesomeday Nov 16 '10 at 11:56
  • @lonesomeday How to do it for objects? For example I tried with ```if($res->data) { ...... }```. But it didn't work. Should I use ```if(isset($res->data))``` ? I am using php 5.6. – Khurshid Alam Jan 07 '16 at 05:35
1

Only thing you need is to check if your variables are set using isset() as that will remove your notice. I believe it's good practice to do so if you plan to use any variable which might not be defined.

Also, if you don't care about the variable being set or not, you might as well use @. ( take a look here in case you don't know what @ is )

I don't think there will be any significant performance difference (being a micro optimization if any) but I believe there is an huge visual improvement if no errors/notices/warnings are shown.

About hiding errors/notices/warnings, take a look here.

Community
  • 1
  • 1
acm
  • 6,541
  • 3
  • 39
  • 44
1

I'd wager that the biggest performance hit would be on Apache writing these errors out to file. The warning generation itself should not be too expensive but you could check by profiling your code with xdebug or similar to be sure.

Surfrdan
  • 505
  • 3
  • 12