Issue
So I was about to write something like following code
switch ($mode) {
case 'all':
foreach ($sortInfo as $info) $filter[] = array_merge([$info->maincat], $info->subcats);
break;
case 'sub':
foreach ($sortInfo as $info) $filter[] = $info->subcats;
break;
default:
foreach ($sortInfo as $info) $filter[] = [$info->maincat];
break;
}
Then I told myself "hey, wouldn't it be more optimized if I wrapped the whole switch inside the for loop?"
foreach ($sortInfo as $info) {
switch ($mode) {
case 'all':
$filter[] = array_merge([$info->maincat], $info->subcats);
break;
case 'sub':
$filter[] = $info->subcats;
break;
default:
$filter[] = [$info->maincat];
break;
}
}
But while it does technically save a bit (get it?) of filesize, the loop would confirm the same information in the switch statement for each iteration of the loop.
I figured there is no objective way to determine which is fastest because it depends on the length of $sortinfo
, but since it's the first time I come across this dilemma, I'd like to know if there's a preferred method, or what's your take on it.
Solution
Since you will only be running this once, any performance difference is entirely negligible. You could benchmark with a fixed dataset if you had to run it thousands of times, though still I doubt that you'd see more than a +/- 10% difference. Choose whichever version you find more readable. If you want to save bits and are running PHP 8, you can do:
$cats = match($mode) {
'all' => array_merge(
array_column($sortInfo, 'maincat'), ...array_column($sortInfo, 'subcats')
),
'sub' => array_merge(...array_column($sortInfo, 'subcats')),
default => array_column($sortInfo, 'maincat')
};
Updated: Per OP's revision, maincat
is a single scalar and subcats
is an array of scalars. Since we want to have a 1-D array in all modes, we use the ...
splat operator to "dish out" the subcategories into the array_merge
, which gives us a "flat" array. Demo: 3v4l.org/NasiC
That's 227 bits vs. 338 bits in your "switch in foreach" vs. 346 bits in your "foreach in switch" or a 33% reduction. I find this approach very readable and free of avoidable verbosity.
If you're still runnning PHP 7, you can factor this approach into a switch:
switch ($mode) {
case 'all':
$cats = array_merge(
array_column($sortInfo, 'maincat'), ...array_column($sortInfo, 'subcats')
);
break;
case 'sub':
$cats = array_merge(...array_column($sortInfo, 'subcats'));
break;
default:
$cats = array_column($sortInfo, 'maincat');
break;
};
That's still only 299 bytes. :) N.B. match
was one of my major reasons for upgrading early to PHP 8. Premium sugar for a number of dishes, eliminates a lot of boilerplate code.
Answered By - Markus AO Answer Checked By - Terry (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.