Skip to content

Evaluate count() once per loop instead of once per iteration - #12837

Open
mukeshpanchal27 wants to merge 7 commits into
WordPress:trunkfrom
mukeshpanchal27:perf/hoist-count
Open

Evaluate count() once per loop instead of once per iteration#12837
mukeshpanchal27 wants to merge 7 commits into
WordPress:trunkfrom
mukeshpanchal27:perf/hoist-count

Conversation

@mukeshpanchal27

@mukeshpanchal27 mukeshpanchal27 commented Aug 4, 2026

Copy link
Copy Markdown
Member

Trac ticket: https://core.trac.wordpress.org/ticket/65811

Use of AI Tools

AI assistance: Yes
Tool(s): Claude
Model(s): Opus 5
Used for: Initial code skeleton and test suggestions; final implementation and tests were reviewed and edited by me.


This Pull Request is for code review only. Please keep all other discussion in the Trac ticket. Do not merge this Pull Request. See GitHub Pull Requests for Code Review in the Core Handbook for more details.

mukeshpanchal27 and others added 2 commits July 30, 2026 20:42
…eration.

A `for` condition runs once per iteration plus once to terminate, so
`$i < count( $array )` calls `count()` n + 1 times to walk an n-element array
whose length never changes. Compute the bound in the loop initialiser instead,
matching the idiom already used throughout core.

`register_block_type_from_metadata()` is the main beneficiary: it runs for every
registered block on every request, and the affected loops sit inside `foreach`
blocks covering three script fields and three style fields each.

In every case the iterated array is provably invariant across the loop body, so
there is no behaviour change.

Props mukesh.
@mukeshpanchal27 mukeshpanchal27 self-assigned this Aug 4, 2026
@github-actions

github-actions Bot commented Aug 4, 2026

Copy link
Copy Markdown

Test using WordPress Playground

The changes in this pull request can previewed and tested using a WordPress Playground instance.

WordPress Playground is an experimental project that creates a full WordPress instance entirely within the browser.

Some things to be aware of

  • All changes will be lost when closing a tab with a Playground instance.
  • All changes will be lost when refreshing the page.
  • A fresh instance is created each time the link below is clicked.
  • Every time this pull request is updated, a new ZIP file containing all changes is created. If changes are not reflected in the Playground instance,
    it's possible that the most recent build failed, or has not completed. Check the list of workflow runs to be sure.

For more details about these limitations and more, check out the Limitations page in the WordPress Playground documentation.

Test this pull request with WordPress Playground.

@mukeshpanchal27
mukeshpanchal27 marked this pull request as ready for review August 5, 2026 04:44
@github-actions

github-actions Bot commented Aug 5, 2026

Copy link
Copy Markdown

The following accounts have interacted with this PR and/or linked issues. I will continue to update these lists as activity occurs. You can also manually ask me to refresh this list by adding the props-bot label.

Core Committers: Use this line as a base for the props when committing in SVN:

Props mukesh27, westonruter, afercia.

To understand the WordPress project's expectations around crediting contributors, please review the Contributor Attribution page in the Core Handbook.

@afercia

afercia commented Aug 5, 2026

Copy link
Copy Markdown
Member

Thanks for your PR @mukeshpanchal27
It appears Claude missed something here. I would suggest to consider moving the call to count() outside the loop entirely. With the current approach, for example:

for ( $index = 0, $script_count = count( $scripts ); $index < $script_count; $index++ ) {

there's still one function call per loop iteration, it was just moved to the initialization part.

Instead, moving the count() outside the loop entirely and storing the result in a variable:

  • Eliminates any function calls during loop iterations.
  • Calls count() only once, before the loop starts.
  • Is more readable and clear in intent.
  • Provides maximum performance benefit.
$script_count = count( $scripts );
for ( $index = 0; $index < $script_count; $index++ ) {
    ...

@mukeshpanchal27

Copy link
Copy Markdown
Member Author

@afercia Thanks for the feedback it's not addressed. Please take a look when you have moment.

Comment on lines +680 to +681
$script_count = count( $scripts );
for ( $index = 0; $index < $script_count; $index++ ) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alternatively:

Suggested change
$script_count = count( $scripts );
for ( $index = 0; $index < $script_count; $index++ ) {
foreach ( range( 0, count( $scripts ) - 1 ) as $index ) {

However, given that range() doesn't use a generator, this means that the full array has to be in memory. But in reality, it's not many!

So I think this is a better approach.

@mukeshpanchal27 mukeshpanchal27 Aug 7, 2026

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Gemini share response:

These two approaches use entirely different paradigms—and in PHP, the second option (foreach with range()) introduces severe memory overhead and hidden performance issues.

Here is how they compare and why you should avoid range() for looping over arrays.


Comparison

  • for loop (Option 1): Fast and memory-efficient. Calculates array length once ($script_count) and iterates using standard integer incrementation.
  • foreach( range(...) ) (Option 2): Creates an entire second array in memory filled with integers from 0 to count($scripts) - 1 before the loop even starts.

Key Issues with foreach( range(...) )

1. Memory Overhead
If $scripts contains 10,000 items, range(0, 9999) allocates a brand-new array of 10,000 integers in RAM just to serve as the loop counter.

2. Off-by-One Bugs on Empty Arrays
If $scripts is empty (count($scripts) is 0), range(0, -1) will produce [0, -1]. Your loop will attempt to run twice instead of zero times, leading to Undefined array key warnings.

3. Unnecessary Complexity
Iterating over array indices with foreach + range defeats the purpose of foreach.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How many items are we talking about here, though?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The theoretical performance concern would be addressed by a generator, which I noted above that PHP doesn't use unfortunately. Nevertheless, I don't believe the number of items is particularly large.

That said, I don't feel strongly about using range().

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! That said, can we mark this conversation as resolved?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It won't hurt, and changing it can reduce code smell so others don't raise this in the future.

I would suggest, however, that the count initializer be placed inside the for loop, like this:

for (
    $index = 0, $script_count = count( $scripts );
    $index < $script_count;
    $index++ 
) {

Or for a common idiom for naming:

for ( $i = 0, $len = count( $scripts ); $i < $len; $i++ ) {

This can be found in core (via 3rd party libraries), for example:

for ($i = 1, $len = count($bytes); $i < $len; $i++) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Another example:

for ( $i = 1, $c = count( $textarr ); $i < $c; $i += 2 ) {

There quite a few.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Initially i propose that 83e095b but based on the #12837 (comment) feedback i apply that suggestion.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would suggest, however, that the count initializer be placed inside the for loop, like this:

Asking as a learning opportunity: what would be the advantage? That way, count() is called at each loop iteration and the same variable is set again and again at each loop iteration. That seems completely unnecessary to me. If there are other places where this pattern is in used, then I'd argue it should be imporved there as well.
I know there are many occurrences of similar patterns, also on the JS side. That doesn't mean they are entirely OK.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Once this is finalized, I'll open a separate PR to address the other occurrences. That's my plan as a follow-up.

@westonruter westonruter left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion to use range() instead for these instances.

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.

3 participants