0

If I am creating an array from some results from an sql query like so:

$res[] = self::create_array($q2->row_array());

wouldn't it be faster to do if (isset($res[0])) rather than if (count($res) > 0)? The size of some of the results arrays are around 1500 elements; or is the optimization in this area negligible?

tenub
  • 3,386
  • 1
  • 16
  • 25
  • 1
    easy enough to bench mark it to determine the speed difference –  Dec 02 '13 at 01:22
  • 1
    A very quick 'n' dirty comparison at `https://eval.in/74973` suggests that `isset()` is significantly faster. But as @Sverri M. Olsen states below the functions are not synonymous. And `empty()` seems also pretty fast. – Darragh Enright Dec 02 '13 at 01:52

2 Answers2

2

Using isset() is probably faster in this case

The two functions are not synonymous, though:

  • isset() figures out if an array index is set, and
  • count() counts how many items there are in an array

In this particular case you could use either function, but you should use them according to what you are trying to do.

If all you want is to see if an array is empty or not then the empty() function would be what you are looking for. It returns true if the array is empty, and false if it is not empty.

Sverri M. Olsen
  • 13,055
  • 3
  • 36
  • 52
2

Assuming that create_array returns a PHP array, then count is "Just as Fast" - or rather, both operations are O(1) - and does not depend upon the size of the array. This is because arrays store their size internally.

That being said, if create_array returns an arbitrary Countable, then the count may have to do more work, depending upon how the returned object is implemented - imagine if an object implemented as a Single-Linked List was returned; this would require O(n) time to count.

In any case, using empty is more semantically clear and, as shown by a small micro-benchmark by Darragh, performs the same as isset in wall-clock time.

See also: Is PHP's count() function O(1) or O(n) for arrays?

Community
  • 1
  • 1
user2864740
  • 60,010
  • 15
  • 145
  • 220