Zend: Optimize sorting single-element arrays - #23550
Conversation
|
unless Gina beats me to it, I ll review a bit later seems good not entirely sure it s bug free |
|
I know it s performance oriented and with your last change it seems ok, but try to think of a test oriented regression, e.g. making sure a refactoring does not break it. |
|
Thanks ! |
|
Is this really a case worth optimising? How often does one actually try to sort a single element array? |
It makes no sense to sort an empty array either. But we have a fast-path for it. Not mentioning sorting one-element array actually has some meaningful behaviors. |
yeah I don't know why we are optimising empty arrays at least that should just be something the optimizer decides it can elide and not the function handling it... |
I think it is meaningful for these fast-path optimizations. It doesn't have downside anyways and AFAIK the parameters of sort is usually dynamic, in many cases it might be sorting empty or single arrays. And yes, I think of migrating it to optimizer before. I am not familiar with it and I don't sure it can be smart enough to catch all cases. If it is this might be a good follow-up |
Now,
zend_array_sort()useszend_array_sort_ex(), which unpacks packed arrays and temporarily increments the array refcount to protect against the comparator freeing the array.Obviously this is useless for one-element arrays. Here, we can just use
zend_hash_sort_exinstead for this case.Some may ask what's the meaning to sort one-element array anyways. This can't be similar to what sorting zero-element array do, which is directly returning the empty array. Because the sorting functions have other things to do rather than just sort the elements.
Here, we remain the original sort behavior for one-element array while making it faster because we are not actually sorting them
benchmark results:
After: 448.923 ms
Before: 905.807 ms
a roughly 50.4% enhancement in this specific case.
script: