yii2 icon indicating copy to clipboard operation
yii2 copied to clipboard

Minor optimisation in ArrayHelper::map()

Open chriscpty opened this issue 1 year ago • 1 comments

When both $from and $to are strings referring to a field and $group is null, ArrayHelper::map() can be sped up by simply using php's built-in array_column. I'll create a pull request for this in a second too.

My benchmark program (running in a project I'm currently working on) looks like this:

$companies = Company::find()->all();

for ($i = 0; $i < 5; $i++) {
    $before = microtime(true);

    $res = ArrayHelper::map($companies, 'id', 'name');

    $after = microtime(true);
    echo 'before: ' . $before . '<br />after: ' . $after;
    echo '<br />elapsed: ' . ($after - $before);
    echo '<hr />';
}

echo '<br />bench size: ' . count($res);

Output without the optimisation:

before: 1729170541.9258
after: 1729170542.8095
elapsed: 0.88366889953613
before: 1729170542.8095
after: 1729170543.6844
elapsed: 0.87490391731262
before: 1729170543.6844
after: 1729170544.5437
elapsed: 0.85927605628967
before: 1729170544.5437
after: 1729170545.3944
elapsed: 0.85066390037537
before: 1729170545.3944
after: 1729170546.2858
elapsed: 0.89145588874817

With the optimisation added:

before: 1729170492.2701
after: 1729170493.0914
elapsed: 0.82133507728577
before: 1729170493.0914
after: 1729170493.8881
elapsed: 0.79668998718262
before: 1729170493.8881
after: 1729170494.6662
elapsed: 0.77812695503235
before: 1729170494.6662
after: 1729170495.4399
elapsed: 0.77362585067749
before: 1729170495.4399
after: 1729170496.249
elapsed: 0.80916404724121

While small, this optimisation could still help when processing big chunks of data.

Additional info

Q A
Yii version dev-master
PHP version 8.1
Operating system debian 12

chriscpty avatar Oct 17 '24 13:10 chriscpty

Good catch. Will review shortly. Thanks.

samdark avatar Oct 17 '24 13:10 samdark