Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[11.x] Replace while loop with array_walk #51802

Closed
wants to merge 2 commits into from

Conversation

seriquynh
Copy link
Contributor

Inside Foundation\Application and Support\ServiceProvider classes, there is code that executes callbacks sequentially like this:

protected function fireAppCallbacks(array &$callbacks)
{
    $index = 0;

    while ($index < count($callbacks)) { // count function is called on every callback.
        $callbacks[$index]($this);

        $index++;
    }
}

The while loop can be replaced with array_walk like code below. Then, no need to initialize and increase $index variable, unnecessary count calls are removed.

protected function fireAppCallbacks(array &$callbacks)
{
    array_walk(
        $callbacks, fn($callback) => $callback($this)
    );
}

Plus: I add tests to ensure booting/booted callbacks are executed sequentially.

@dennisprudlo
Copy link
Contributor

Isn't it possible that one of those callbacks will add more callbacks to the list? And if so, does array_walk consider this?

@henzeb
Copy link
Contributor

henzeb commented Jun 15, 2024

Isn't it possible that one of those callbacks will add more callbacks to the list? And if so, does array_walk consider this?

Just so you know: yes it does. But a while loop is slightly bit faster...

@seriquynh seriquynh deleted the replace-while-loop branch June 17, 2024 08:31
@seriquynh
Copy link
Contributor Author

Screenshot 2024-06-17 153258

@dennisprudlo I think we can use array_map but do nothing with it's returned result.

@henzeb If while loop is still used this case, we shouldn't call count function inside condition section "while ($index < count($callbacks))", should we?

For me, Laravel code is unpredictable, decisions are sometimes randomly accepted, a bit inconsistent.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants