Skip to content

Minor optimisation in ArrayHelper::map() #20268

@chriscpty

Description

@chriscpty

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions