Make WordPress Core

Opened 4 years ago

Closed 4 years ago

Last modified 4 years ago

#43891 closed enhancement (invalid)

Performance improvement for WP_Query

Reported by: rnaby Owned by:
Milestone: Priority: normal
Severity: normal Version:
Component: Query Keywords: has-patch needs-testing
Focuses: Cc:


WP_Query has some(10 I think) use of reset() function. But it has a performance drawback. So here I'm proposing to replace the PHP native reset() function with class method which will work with foreach() loop.

Here is the benchmark-

Attachments (1)

43891.diff (3.6 KB) - added by rnaby 4 years ago.
The patch for the issue.

Download all attachments as: .zip

Change History (5)

4 years ago

The patch for the issue.

#1 @johnbillion
4 years ago

  • Keywords reporter-feedback added; 2nd-opinion dev-feedback removed
  • Severity changed from major to normal
  • Version trunk deleted

Thanks for the ticket and the patch, @rnaby, but I think your benchmarks are flawed. If you add judge($a, 'reset'); to the end of the test (after judge($a, '_reset'); you'll see that directly calling reset() is faster than the other methods. Your _reset() function incurs overhead that the reset() function doesn't.

Can you confirm?

Last edited 4 years ago by johnbillion (previous) (diff)

#2 @rnaby
4 years ago

@johnbillion . I tried putting the judge functions one above another and the results are pretty similar. Please have a look at the screenshot.


Here is the testing script-


function _reset( $array ) {
	return reset($array);

function _foreach( $array ) {
	foreach( $array as $el ) {
	    return $el;

function judge($array, $method) {
    $loop = 10000;

    $time = microtime(true);

    for ($i = 0; $i < $loop; ++$i) {
        $temp = $method($array);

    $time = microtime(true) - $time;

    echo implode(PHP_EOL, [
        "  Time: {$time}s",
        "  Result: {$temp}",

$a = [];

$index = 0;

for ($i = 0; $i < 10000; ++$i) {
    $index += rand(1, 5);

    $a[$index] = substr(md5(rand()), 0, rand(3, 7));

judge($a, '_foreach');
judge($a, '_reset');
Version 1, edited 4 years ago by rnaby (previous) (next) (diff)

#3 @rnaby
4 years ago

  • Resolution set to worksforme
  • Status changed from new to closed

#4 @SergeyBiryukov
4 years ago

  • Keywords reporter-feedback removed
  • Milestone Awaiting Review deleted
  • Resolution changed from worksforme to invalid
Note: See TracTickets for help on using tickets.