Skip to content

Instantly share code, notes, and snippets.

@dharkness
Created September 26, 2012 01:55
Show Gist options
  • Save dharkness/3785557 to your computer and use it in GitHub Desktop.
Save dharkness/3785557 to your computer and use it in GitHub Desktop.
Benchmark: foreach vs. array_map
<?php
function benchmark($label, $callback) {
$start = microtime(true);
$callback();
$time = microtime(true) - $start;
echo "Run $label took " . number_format(1000 * $time, 3) . " ms\n";
}
class User {
public $email;
public function __construct() { $this->email = 'user' . rand(0, 10000) . '@email.com'; }
}
function getUserEmail($user) { return $user->email; }
$users = array();
for ($i = 0; $i < 8000; $i++) {
$users[] = new User;
}
benchmark('foreach', function () use ($users) {
$emails = array();
foreach ($users as $user) {
$emails[] = getUserEmail($user);
// $emails[] = $user->email;
}
});
benchmark('array_map', function () use ($users) {
$emails = array_map('getUserEmail', $users);
// $emails = array_map(function ($user) { return $user->email; }, $users);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment