Adrian C.
Adrian C.

Reputation: 762

PHP execution times on second run of the same code

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);

Upvotes: 3

Views: 97

Answers (1)

Ihor Burlachenko
Ihor Burlachenko

Reputation: 4905

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.

Upvotes: 4

Related Questions