views:

56

answers:

1

What will work faster? How strongly will it affect productivity?

$test = new Test();
$a1 = array();
$a2 = array();
$a3 = array();

$a1[1] = $test;
$a2['qwe'] = $test;
$a3[] = $test;
+4  A: 

As no one answered, I've made some test

The code:

<?php

class O
{
}

$test = new O;
$a1 = array();
$a2 = array();
$a3 = array();

$start = microtime(true);
for ($k = 0; $k < 1000000; $k++)
    $a1[1] = $test;
$time[1] = microtime(true)-$start;

$start = microtime(true);
for ($k = 0; $k < 1000000; $k++)
    $a2['qwe'] = $test;
$time[2] = microtime(true)-$start;

$start = microtime(true);
for ($k = 0; $k < 1000000; $k++)
    $a3[] = $test;
$time[3] = microtime(true)-$start;


print_r($time);

The results:

Array ( [1] => 0.18384599685669 [2] => 0.19556093215942 [3] => 0.3099570274353 )

Third one is the slowest one, but mostly because it actually allocates million objects and first two overwrite object on each pass. When I modified first to $a1[$k] = $test;, the results were similar (although don't run it on a low memory limit, say below 128MB).

The conclusion: as we said before, it doesn't really matter. Focus on writing code which is readable and utilizes design patterns, not on some minor optimizations.

Tomasz Struczyński
Pay attention, I assigned a MILLION objects (though small) on each test, and it took so little time.
Tomasz Struczyński
It actually depend on the number of iterations. One solution could be really faster on a $k < 100 for instance (I used to make optimizations once).
Kaaviar
Yeah, but looking at the overall time of this operation... In 99.99% cases it doesn't really matter.
Tomasz Struczyński
and in the other 0.01%, it really doesn't matter
Wim