Skip to content

Instantly share code, notes, and snippets.

@GordonLesti
Last active August 29, 2015 14:13
Show Gist options
  • Select an option

  • Save GordonLesti/23272e3f7c89359bb6a2 to your computer and use it in GitHub Desktop.

Select an option

Save GordonLesti/23272e3f7c89359bb6a2 to your computer and use it in GitHub Desktop.
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

Copy link
Copy Markdown
Author

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