Created
September 26, 2012 01:55
-
-
Save dharkness/3785557 to your computer and use it in GitHub Desktop.
Benchmark: foreach vs. array_map
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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