Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP execution times on second run of the same code

Tags:

php

I have a curiosity. I created a simple php script that creates an array of 1 mil simple array elements and then loops through them.

On the first execution, it seems to take about ~1,4 seconds. But on the second execution of the same code, it always takes about ~2,1 seconds. I've repeated this several times with the same results.

Why is this?

Code sample here:

    $timeStart = microtime(true);

    $invoices = array();
    for ($i = 1; $i <= 1000000; $i++) {
        $invoices[] = array(
            'issuedValue' => $i,
            'fiscalNumber' => $i,
            'random1' => $i,
            'random2' => $i,
            'random3' => $i,
        );
    }
    foreach ($invoices as $invoice) {
        // nothing here
    }

    var_dump(microtime(true) - $timeStart);

    // second iteration here

    $timeStart = microtime(true);

    $invoices = array();
    for ($i = 1; $i <= 1000000; $i++) {
        $invoices[] = array(
            'issuedValue' => $i,
            'fiscalNumber' => $i,
            'random1' => $i,
            'random2' => $i,
            'random3' => $i,
        );
    }
    foreach ($invoices as $invoice) {
        // nothing here
    }

    var_dump(microtime(true) - $timeStart);
like image 435
Adrian C. Avatar asked Dec 03 '25 17:12

Adrian C.


1 Answers

It happens because of memory usage which also increases the chance that garbage collection cycles trigger during the second run. If you add the following code between runs:

unset($timeStart, $invoices, $i, $invoice);
gc_collect_cycles();

to remove references and clean unused memory, you'll get the same time.

like image 97
Ihor Burlachenko Avatar answered Dec 07 '25 23:12

Ihor Burlachenko