Reputation: 372
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.
Upvotes: 0
Views: 192
Reputation: 372
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.
Upvotes: 2