1

Is there any performance difference between this two ones ?

$rules['a']['x'] = 'someValue';
$rules['a']['y'] = 'anotherValue';

and

$rules['a'] = [
    'x' => 'someValue',
    'y' => 'anotherValue',
];
Aram810
  • 619
  • 7
  • 21
  • 1
    [1st](https://3v4l.org/pI9Ap/perf#output) and [2nd](https://3v4l.org/EjVfZ/perf#output), I doubt it will make much of a difference. – Script47 Apr 26 '17 at 07:40
  • 3
    You can test for yourself. Do something like `$startTime = microtime(true); for($i=0;$i<100000;$i++){$rules['a']['x'] = 'someValue'; $rules['a']['y'] = 'anotherValue';} echo 'total time = ' . microtime(true) - $startTime;` and the same for the orher case. But i also doub't it will make a great difference. – Tobias F. Apr 26 '17 at 07:45
  • @Tobias F yes exactly i was also suggesting this one – lazyCoder Apr 26 '17 at 07:46
  • 2
    @Aram810 try this link for your question http://stackoverflow.com/questions/1200214/how-can-i-measure-the-speed-of-code-written-in-php – lazyCoder Apr 26 '17 at 07:46

1 Answers1

2

As noted by everybody else, any difference would be neglible and you shouldn't care about this.

That being said though, the second method should technically be more performant, because (at least it looks like) it does the entire thing in a single instruction.

When you do this:

$rules['a']['x'] = 'someValue';
$rules['a']['y'] = 'anotherValue';

... the PHP engine has to first check whether $rules exists, whether it's an array, an ArrayAccess object or not (and error in that case). After that, it has to do the same for $rules['a'].
And it has to do that twice because both lines represent separate expressions.

While on the other hand:

$rules['a'] = [
    'x' => 'someValue',
    'y' => 'anotherValue',
];

... will only check what $rules is (not caring whether $rules['a'] exists or what type it is) and it only has to do that once.


Note that this is a very, very simplified explanation and there are a lot of other factors that come into play and make a difference. But that's the benefit of using a high-level language like PHP - in general, you don't have to care or even know how things work behind the scene.

If you want to make performance optimizations, this is certainly the wrong thing to look at. Find where your "bottlenecks" are and work on them (pro tip: 9 times out of 10, it's your database queries).

Narf
  • 14,600
  • 3
  • 37
  • 66