Current options_for_select() realization checks whether each option is selected by using the in_array() function which run in O(n) time, therefore the whole complexity is estimated by O(n*m) where n = count($selected) and m = count($options). This is an overkill because this checking can be performed in just O(m) using strength of php assoc. arrays.
Also it's wise to always cast $selected to array.
The code I've been using for benchmarking is the following:
- Lightweight variant:
$options = range(0, 5);
$selected = range(0, 0); // select one out of five elements
for ($i = 0; $i < 500; $i++) {
options_for_select2($options, $selected);
options_for_select($options, $selected);
}
- In this case sum of self time of my function is 297 ms, sum of inclusive is 1108ms.
- Sum of self time of the original function is 477ms, sum of inclusive is 1304ms.
- Heavy variant:
$options = range(0, 1000);
$selected = range(500, 1000); // select 500 out of 1000 elements
for ($i = 0; $i < 5; $i++) {
options_for_select2($options, $selected);
options_for_select($options, $selected);
}
- In this case sum of self time of my function is 450 ms (minimal is 72ms), sum of inclusive is 1973ms.
- Sum of self time of the original function is 648ms (minimal is 126ms), sum of inclusive is 2470ms.
So I would estimate this overall optimization as 20%.