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