Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
PHP Array Fill Benchmark
<?php
$max = 10000000;
$testValues = range(1, $max);
echo php_uname();
echo "\nFill Array with appending elements and for loop\n";
$time = microtime(true);
$newArray = [];
for ($i = 0; $i < $max; $i++) {
$newArray[] = $testValues[$i];
}
$timeDiff = microtime(true) - $time;
echo sprintf("\t%f sec\n", $timeDiff);
echo "\nFill Array with pushing elements and for loop\n";
$time = microtime(true);
$newArray = [];
for ($i = 0; $i < $max; $i++) {
array_push($newArray, $testValues[$i]);
}
$timeDiff = microtime(true) - $time;
echo sprintf("\t%f sec\n", $timeDiff);
echo "\nFill Array with replacing elements and for loop\n";
$time = microtime(true);
$newArray = array_fill(0, $max, 0);
for ($i = 0; $i < $max; $i++) {
$newArray[$i] = $testValues[$i];
}
$timeDiff = microtime(true) - $time;
echo sprintf("\t%f sec\n", $timeDiff);
echo "\nFill SplFixedArray with for loop\n";
$time = microtime(true);
$newArray = new SplFixedArray($max);
for ($i = 0; $i < $max; $i++) {
$newArray[$i] = $testValues[$i];
}
$timeDiff = microtime(true) - $time;
echo sprintf("\t%f sec\n", $timeDiff);
@GordonLesti

This comment has been minimized.

Copy link
Owner Author

commented Jan 22, 2015

Linux debian 3.2.0-4-amd64 #1 SMP Debian 3.2.65-1+deb7u1 x86_64
Fill Array with appending elements and for loop
2.942950 sec

Fill Array with pushing elements and for loop
8.608578 sec

Fill Array with replacing elements and for loop
3.489419 sec

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.