1

假设我有一组来自用户类的对象。类用户包含属性电子邮件。如何从用户对象数组中创建一个电子邮件属性数组?

有没有比以下更好/更快的方法:

$emails = array();
foreach($users as $user) {
   $emails[] = $user->email;
}
4

2 回答 2

3

您可以使用array_mapwhich 将在 C 中进行循环,但每次迭代都需要回调 PHP。

$emails = array_map(function ($user) { return $user->email; }, $users);

更好的?

The above code is more expressive to me and probably most functional programmers, but that's subjective. It also requires PHP 5.3 for the callback. You can get around that for PHP 5.2 and below by declaring a global function, but then you lose much of the clarity, especially when the code appears in a class.

function getUserEmail($user) { return $user->email; }
$emails = array_map('getUserEmail', $users);

Faster?

In this simple case with the callback, it seems to be slower (see Esben's answer). However, I have two caveats here.

  1. Micro-benchmarks are notoriously finicky. They vary from machine to machine and depend on the particular build of the interpreter. But worse, measuring such a small value can be overshadowed by other tasks such as processor multitasking, memory management, etc. The times also varied considerably between using the callback versus the global function.

  2. Developer time is far costlier than CPU cycles. You're better off writing the easiest-to-code and maintain solution first and only optimizing it once you've a) found it to be a problem and b) measured how much of a problem it is. Obviously this is much less important for this simple case, but it's a general rule I've learned to follow.

于 2012-09-26T00:58:28.740 回答
0

看起来 foreach 循环是最快的。我猜语法是一个品味问题。

编辑

正如我在回复 David 的帖子时所说的那样,我实际上已经对此进行了基准测试。

for($i = 0;$i<=8000;$i++){
    $users[] = (object)array("email"=>rand(0,15));
}

$arrMapBm = new nzpBM("arrMap");
$foreachBm = new nzpBM("foreach");

$arrMapBm->start();
$emails = array_map(function ($user) { return $user->email; }, $users);
echo $arrMapBm;
unset($emails);

$foreachBm->start();
foreach($users as $user) {
   $emails[] = $user->email;
}
echo $foreachBm;

给出了相当可靠的结果。

The benchmark "arrMap (1)" took 4.8160552978516 miliseconds
The benchmark "foreach (1)" took 2.1059513092041 miliseconds

我不知道这是否是因为我目前在 Windows 机器上,但对我来说,array_map 肯定不会更快。不想在这里误导任何人。

于 2012-09-26T00:56:53.667 回答