0

What is the best (fastest, most readable, etc.) way to create associative array?

Last time I saw that my co-worker, create small assoc array by:

$array['is_enabled'] = false;

In code review i pass my opinion that more readable form is:

$array = [
    'is_enabled' => false
];

But "readable" is subjective thing, so it's not the best argument.

  • Generally when you want end up with a constant data structure, it's better to declare it in the second form. Nobody is interested in how you create an empty array, then piece it together key by key, it's just more stress on the reader. Just my take on this. – Balázs Édes Oct 15 '17 at 17:45
  • 1
    Also I'm pretty sure the first method generates PHP warnings. – marekpw Oct 15 '17 at 17:52
  • @marekpw with symfony and PHP 7.1 it doesn't throw any error, even notice. Even 3v4l should show some PHP warnings if they occures, as I know. – Sebastian Tkaczyk Oct 16 '17 at 08:56
  • Don't worry about fastest. Worry about what is the most readable and expresses your intent best. – Andy Lester Oct 19 '17 at 21:29
  • @AndyLester As I wrote, more readable is second option. I found that it's also faster than first. So I want to share that know, and I created question with my response. And maybe somebody someday will use this :) – Sebastian Tkaczyk Oct 19 '17 at 22:00

1 Answers1

2

The first approach 3v4l link:

$subscription['is_enabled'] = false;

You can see in link that's generated 3 operations

number of ops:  3
compiled vars:  !0 = $subscription
line     #* E I O op                           fetch          ext  return  operands
-------------------------------------------------------------------------------------
   3     0  E >   ASSIGN_DIM                                               !0, 'is_active'
         1        OP_DATA                                                  
         2      > RETURN                                                   1

Avg. memory usage is 25.15 MiB and runs in 0.013s (user time PHP 7.1.x).

The second approach 3v4l link:

$subscription = ['is_active' => false];

Now it's only 2 operations. Assign and return.

number of ops:  2
compiled vars:  !0 = $subscription
line     #* E I O op                           fetch          ext  return  operands
-------------------------------------------------------------------------------------
   3     0  E >   ASSIGN                                                   !0, 
         1      > RETURN                                                   1

Avg. memory usage is 24.40 MiB and runs in 0.010s (user time PHP 7.1.x).

I'm not sure what operation is op_data that is missing in second approach. But still it's one operation less, and in result we gain almost 0,8MiB less memory usage and ~23% faster execution time.


So it's looks like $array= ['key' => false];

It's not only more readable but also quite simpler for parser. With this notation we skip one operation from three, and that's give us additional free memory and time.