Search code examples
phparraysexecution-time

Speed increase by fixing notices regarding arrays?


I have a PHP script that is making various calls to Instagram's API and then assigns them to arrays to display later.

It does so as such:

array_push($this->url_array, $result->data[$i]->link);

It does the same thing for multiple fields.

Now, being as that not every returned post is going to have all the same data I'm frequently getting notices as such:

Notice: Undefined offset: 2

I can easily remove these with the following code

if($result->data[$i]->link != NULL)
{
  array_push($this->url_array, $result->data[$i]->link)
}
else
{
   array_push($this->url_array, NULL);
}

I need to always have some value in there or else it messes up displaying the tables later as each array I generate needs to be the same length.

My question is, will I see any speed improvement using the IF statement as opposed to just hiding the notices? The script works as intended both ways, but I'm at the stage where I want to optimize it as much as possible. Is it worth it to write the 10 or so array pushes in the IF statement?

My initial intuition would be no, since it's still adding one element to the array in either case. However, I don't know how PHP handles the errors behind the scenes, and if that process adds extra time or not.


Solution

  • It turns out doing the IF statement is indeed much more faster.

    After some testing I was able to effectively double the speed of script by checking for the value before attempting to assign it

    No matter how the error reporting is set, in the background PHP still generates and formats the notice message. So regardless of whether it's displayed to the screen it is still spending time and resources creating these errors, which seems to be a heavy drag on time.