Understanding PHP Generators

yeild 是當數(shù)據(jù)被使用時奶稠,才會生成,可以理解為不消耗內(nèi)存捡遍。也可以生成關(guān)聯(lián)數(shù)組锌订,只能在函數(shù)中使用。

數(shù)組則是提前生成好數(shù)據(jù)集画株,存儲在內(nèi)存中辆飘。當數(shù)據(jù)集足夠大時,會出現(xiàn)耗盡內(nèi)存的情況谓传。

yield keyword

The heart of a generator function is the yield keyword. In its simplest form, a yield statement looks much like a return statement, except that instead of stopping execution of the function and returning, yield instead provides a value to the code looping over the generator and pauses execution of the generator function.

When it comes to driving, speed is not everything. But on the web, speed makes all the difference. The faster your application, the better the user experience. Well, this article is on PHP Generators, so why are we talking about speed? As you are soon about to find out, generators make a huge difference on speed and memory management.

#What are PHP Generators?

Added to PHP in version 5.5, generators are functions that provide a simple way to loop through data without the need to build an array in memory. Still a bit confused? An example is a good way to show generators in action.

First, let's quickly create a generator.php file that we will use throughout this tutorial. After creating the file, we add this little code snippet.

Table of Contents

  1. What are PHP Generators?
  2. Using Generators
  3. Why Do This?
  4. Returning Keys
  5. Sending Values to Generator
  6. Don't Misuse Generators
  7. Conclusion
<?php

function getRange ($max = 10) {
    $array = [];

    for ($i = 1; $i < $max; $i++) {
        $array[] = $i;
    }

    return $array;
}

foreach (getRange(15) as $range) {
    echo "Dataset {$range} <br>";
}

We can quickly spin up an inbuilt PHP server in the directory where we created the generator.php file:

The code is pretty much self-explanatory, and this definitely doesn't look like much. But if we go back into our code and make a little change

<?php

foreach (getRange(PHP_INT_MAX) as $range) {
    echo "Dataset {$range} <br>";
}

Now, the upper range(max) of generated numbers is PHP_INT_MAX, which is the largest number that your version of PHP can reach. After doing this, head over to the browser and refresh. But this time, you'll notice something different. The generator script throws a warning error.

fatal error

Well, that's a shame, PHP ran out of memory. Possible solutions that come to mind include going into php.ini and increasing memory_limit. Let's ask ourselves these questions, is this really effective? Do we want a single script to hog all our server's memory? The answers are no and no. This is not effective, and we do not want a single script to use up all our memory.

Using Generators

Let's define the same function above, call it with the same value PHP_INT_MAXand run it again. But, this time, we will be creating a generator function.

<?php

function getRange ($max = 10) {
    for ($i = 1; $i < $max; $i++) {
        yield $i;
    }
}

foreach (getRange(PHP_INT_MAX) as $range) {
    echo "Dataset {$range} <br>";
}

Dissecting the getRange function, this time, we only loop through the values and yield an output. yield is similar to return as it returns a value from a function, but the only difference is that yield returns a value only when it is needed and does not try to keep the entire dataset in memory.

If you head over to your browser, you should see data being displayed on the page. Given the appropriate time, the browser eventually displays the data.

Note: Generators can only be used from a function.

#Why Do This?

There are times when we might want to parse a large dataset (it can be log files), perform computation on a large database result, etc. We don't want actions like this hogging all the memory. We should try to conserve memory as much as possible. The data doesn't necessarily need to be large — generators are effective no matter how small a dataset is. Don't forget, our aim is speed while using less memory.

#Returning Keys

There are times when our data only make sense when they are key-value based. When using generators, we can yield key-value pairs like this.

<?php

function getRange ($max = 10) {
    for ($i = 1; $i < $max; $i++) {
        $value = $i * mt_rand();

        yield $i => $value;
    }
}

We can then go ahead and use the pair as we would do with any array like this.

<?php

foreach (getRange(PHP_INT_MAX) as $range => $value) {
    echo "Dataset {$range} has {$value} value<br>";
}

#Sending Values to Generator

Generators can also take in values. This means that generators allow us to inject values into them, maybe as a command or something. For example, we can send a value to our generator telling to stop execution or change the output. Using the getRange function above, we can do this.

<?php

function getRange ($max = 10) {
    for ($i = 1; $i < $max; $i++) {
        $injected = yield $i;

        if ($injected === 'stop') return;
    }
}

To send inject this value, we can do this.

<?php

$generator = getRange(PHP_INT_MAX);

foreach ($generator as $range) {
    if ($range === 10000) {
        $generator->send('stop');
    }

    echo "Dataset {$range} <br>";
}

NOTE: Using return in a generator breaks out of the generator function.

#Don't Misuse Generators

Using PHP_INT_MAX is a tad overboard. For me, PHP_INT_MAX is 2147483647that is:

two billion one hundred forty-seven million four hundred eighty-three thousand six hundred forty-seven

Generators are supposed to be memory efficient. This doesn't mean that they won't cause the same problem they are trying to solve if misused.

#Conclusion

Generators offer a significant performance boost that we cannot deny. Most times we don't need to have powerful servers to handle our code. We just need to do a little refactoring. Generators are useful and we ought to use them more often than not.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末蜈项,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子良拼,更是在濱河造成了極大的恐慌战得,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,188評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件庸推,死亡現(xiàn)場離奇詭異常侦,居然都是意外死亡,警方通過查閱死者的電腦和手機贬媒,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,464評論 3 395
  • 文/潘曉璐 我一進店門聋亡,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人际乘,你說我怎么就攤上這事坡倔。” “怎么了脖含?”我有些...
    開封第一講書人閱讀 165,562評論 0 356
  • 文/不壞的土叔 我叫張陵罪塔,是天一觀的道長。 經(jīng)常有香客問我养葵,道長征堪,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,893評論 1 295
  • 正文 為了忘掉前任关拒,我火速辦了婚禮佃蚜,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘着绊。我一直安慰自己谐算,他們只是感情好,可當我...
    茶點故事閱讀 67,917評論 6 392
  • 文/花漫 我一把揭開白布归露。 她就那樣靜靜地躺著洲脂,像睡著了一般。 火紅的嫁衣襯著肌膚如雪剧包。 梳的紋絲不亂的頭發(fā)上恐锦,一...
    開封第一講書人閱讀 51,708評論 1 305
  • 那天雇毫,我揣著相機與錄音,去河邊找鬼踩蔚。 笑死,一個胖子當著我的面吹牛枚粘,可吹牛的內(nèi)容都是我干的馅闽。 我是一名探鬼主播,決...
    沈念sama閱讀 40,430評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼馍迄,長吁一口氣:“原來是場噩夢啊……” “哼福也!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起攀圈,我...
    開封第一講書人閱讀 39,342評論 0 276
  • 序言:老撾萬榮一對情侶失蹤暴凑,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后赘来,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體现喳,經(jīng)...
    沈念sama閱讀 45,801評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,976評論 3 337
  • 正文 我和宋清朗相戀三年犬辰,在試婚紗的時候發(fā)現(xiàn)自己被綠了嗦篱。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,115評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡幌缝,死狀恐怖灸促,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情涵卵,我是刑警寧澤浴栽,帶...
    沈念sama閱讀 35,804評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站轿偎,受9級特大地震影響典鸡,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜贴硫,卻給世界環(huán)境...
    茶點故事閱讀 41,458評論 3 331
  • 文/蒙蒙 一椿每、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧英遭,春花似錦间护、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,008評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至多律,卻和暖如春痴突,著一層夾襖步出監(jiān)牢的瞬間搂蜓,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,135評論 1 272
  • 我被黑心中介騙來泰國打工辽装, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留帮碰,地道東北人。 一個月前我還...
    沈念sama閱讀 48,365評論 3 373
  • 正文 我出身青樓拾积,卻偏偏與公主長得像殉挽,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子拓巧,可洞房花燭夜當晚...
    茶點故事閱讀 45,055評論 2 355

推薦閱讀更多精彩內(nèi)容