Skip to content

[New Rule] Slow array SHOULD NOT be used in loop #20

Closed
@lenaorobei

Description

@lenaorobei

Rule

The use of slow array functions (array_merge) in loop is discouraged.

Reason

Merging arrays in a loop is slow and causes high CPU usage. Some benchmarking.

Bad example:

    $options = [];
    foreach ($configurationSources as $source) {
        // code here
        $options = array_merge($options, $source->getOptions());
    }

Good example:

    $options = [];
    foreach ($configurationSources as $source) {
        // code here
        $options[] = $source->getOptions();
    }

    // PHP 5.6+
    $options = array_merge([], ...$options);

Implementation

  • Subscribe to T_STRING token and check if it's content is array_merge.
  • Try to find outer loop.
  • If loop is found rase a warning (need to discuss additional logic).
<severity>7</severity>
<type>warning</type>

Metadata

Metadata

Assignees

Labels

acceptedNew rule is acceptednew ruleNew feature implementationproposalNew rule proposal

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions