php5.5新特性之yield理解
时间:2016-04-27 12:28:36
收藏:0
阅读:4335
今天,在阅读别人代码时,其中出现了一个陌生的关键字yield,想一探究竟,于是找到:http://php.net/manual/zh/language.generators.overview.php
yield生成器是php5.5之后出现的,yield提供了一种更容易的方法来实现简单的迭代对象,相比较定义类实现 Iterator 接口的方式,性能开销和复杂性大大降低。
yield生成器允许你 在 foreach 代码块中写代码来迭代一组数据而不需要在内存中创建一个数组。
使用示例:
/** * 计算平方数列 * @param $start * @param $stop * @return Generator */ function squares($start, $stop) { if ($start < $stop) { for ($i = $start; $i <= $stop; $i++) { yield $i => $i * $i; } } else { for ($i = $start; $i >= $stop; $i--) { yield $i => $i * $i; //迭代生成数组: 键=》值 } } } foreach (squares(3, 15) as $n => $square) { echo $n . ‘squared is‘ . $square . ‘<br>‘; } 输出: 3 squared is 9 4 squared is 16 5 squared is 25 ...
示例2:
//对某一数组进行加权处理 $numbers = array(‘nike‘ => 200, ‘jordan‘ => 500, ‘adiads‘ => 800); //通常方法,如果是百万级别的访问量,这种方法会占用极大内存 function rand_weight($numbers) { $total = 0; foreach ($numbers as $number => $weight) { $total += $weight; $distribution[$number] = $total; } $rand = mt_rand(0, $total-1); foreach ($distribution as $num => $weight) { if ($rand < $weight) return $num; } } //改用yield生成器 function mt_rand_weight($numbers) { $total = 0; foreach ($numbers as $number => $weight) { $total += $weight; yield $number => $total; } } function mt_rand_generator($numbers) { $total = array_sum($numbers); $rand = mt_rand(0, $total -1); foreach (mt_rand_weight($numbers) as $num => $weight) { if ($rand < $weight) return $num; } }
评论(0)