Evaluate count() once per loop instead of once per iteration - #12837
Evaluate count() once per loop instead of once per iteration#12837mukeshpanchal27 wants to merge 7 commits into
count() once per loop instead of once per iteration#12837Conversation
…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.
Test using WordPress PlaygroundThe 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
For more details about these limitations and more, check out the Limitations page in the WordPress Playground documentation. |
|
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 Core Committers: Use this line as a base for the props when committing in SVN: To understand the WordPress project's expectations around crediting contributors, please review the Contributor Attribution page in the Core Handbook. |
|
Thanks for your PR @mukeshpanchal27
there's still one function call per loop iteration, it was just moved to the initialization part. Instead, moving the
|
|
@afercia Thanks for the feedback it's not addressed. Please take a look when you have moment. |
| $script_count = count( $scripts ); | ||
| for ( $index = 0; $index < $script_count; $index++ ) { |
There was a problem hiding this comment.
Alternatively:
| $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.
There was a problem hiding this comment.
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
forloop (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 from0tocount($scripts) - 1before 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.
There was a problem hiding this comment.
How many items are we talking about here, though?
There was a problem hiding this comment.
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().
There was a problem hiding this comment.
Thanks! That said, can we mark this conversation as resolved?
There was a problem hiding this comment.
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:
There was a problem hiding this comment.
Initially i propose that 83e095b but based on the #12837 (comment) feedback i apply that suggestion.
There was a problem hiding this comment.
I would suggest, however, that the count initializer be placed inside the
forloop, 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.
There was a problem hiding this comment.
Once this is finalized, I'll open a separate PR to address the other occurrences. That's my plan as a follow-up.
westonruter
left a comment
There was a problem hiding this comment.
Suggestion to use range() instead for these instances.
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.