php55新增特性yield產生器

來源:互聯網
上載者:User
php官方文檔 yield http://php.net/manual/zh/language.generators.overview.php

參考:http://laravelacademy.org/post/4317.html

產生器提供了一種更容易的方法來實現簡單的對象迭代,相比較定義類實現 Iterator 介面的方式,效能開銷和複雜性大大降低。

產生器允許你在 foreach 代碼塊中寫代碼來迭代一組資料而不需要在記憶體中建立一個數組, 那會使你的記憶體達到上限,或者會佔據可觀的處理時間。相反,你可以寫一個產生器函數,就像一個普通的自訂函數一樣, 和普通函數只返回一次不同的是, 產生器可以根據需要 yield 多次,以便產生需要迭代的值。

$length = 1000000;//產生器foreach (yieldTest($length) as$v1) {    echo$v1;}functionyieldTest($length) {for($i = 0; $i < $length; $i++) {        yield$i . 'Camel';    }}/*迭代器以下的代碼會拋出錯誤:PHP Fatal error:  Allowed memory size of 134217728 bytes exhausted (tried to allocate 72 bytes) in /var/www/test/90/yield/demo01.php on line 38*/foreach(iteratorTest($length) as$v2) {    echo$v2;}functioniteratorTest($length) {$data = [];    for($i = 0; $i < $length; $i++) {        $data[] = $i . 'Camel';    }    return$data;}

如果要使用特定方式計算大量資料,如操作Excel表資料,對效能影響更甚。此時我們可以使用產生器,即時計算併產出後續值,不佔用寶貴的記憶體空間,使用的記憶體更少。

').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($('
  • ').text(i)); }; $numbering.fadeIn(1700); }); });

    以上就介紹了 php55新增特性yield產生器,包括了方面的內容,希望對PHP教程有興趣的朋友有所協助。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.