Skip to content

Instantly share code, notes, and snippets.

@mardix
Created May 5, 2014 18:50
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mardix/38895305786610152efa to your computer and use it in GitHub Desktop.
Save mardix/38895305786610152efa to your computer and use it in GitHub Desktop.
array_map is slower and more of memory hug than foreach in PHP
While I was working on a personal project, I decided to compare foreach vs array_map to iterate over a large set of items.
So to support my decision, I ran a benchmark on both foreach and array_map.
With a simple array of 1,000,000 objects, I iterate over them with foreach and array_map. And surprisingly, foreach ran in 0.24sec average, while array_map took over 3.30sec.
Also array_map ran out of memory, I had to do an ini_set("memory_limit","512M"); to at least get some results.
My system:
Macbook
PHP: 5.5
RAM: 16GB
Processor: 2.3GHz i7
-> FOREACH
<?php
$data = range(0, 1000000);
$start = microtime(true);
$r = [];
foreach($data as $d) {
$r[] = $d;
}
echo microtime(true) - $start;
-> ARRAY_MAP
<?php
ini_set("memory_limit","512M");
$data = range(0, 1000000);
$start = microtime(true);
$r = array_map(function($d){
return $d;
}, $data);
echo microtime(true) - $start;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment