You are viewing a single comment's thread from:

RE: PHP: Use associative arrays basically never

in #php6 years ago

How about using the array_multisort() instead of usort():

array_multisort(
      $list, 
      array_column($list,'a'), 
      array_column($list, 'b')
);

Running on a mac book pro, 2.2GHz Intel Core i7, 16GB, listing Av. of 3 runs:

Associative array (Sorting)

MethodRuntime (s)Memory (bytes)
usort15.6589 (s)541414232 bytes (516.33 MB)
array_mulitsort8.8314 (s)706785816 bytes (674.04 MB)

Object with public properties (sorting):

MethodRuntime (s)Memory (bytes)
usort12.9263 (s)253795352 bytes (242.04 MB)
array_mulitsort7.6217 (s)419166808 bytes (399.75MB)

a tradeoff between memory and runtime ...

Sort:  

Interesting observation! If you're sorting an array, yes, that would make a big difference. However, the purpose of usort() here was to provide a direct comparison between objects and arrays, so they had to be used in the same way. That meant usort() so that we could compare the property access in each. I didn't as much care about the sorting itself as sorting was an easy way to call $array['a'] and $object->a a few zillion times. :-)