Monday 15 July 2013

php - What is the difference between a generator and an array? -


The PHP team has released version today, which includes support for generators . Reading, I saw that it does precisely what it can do with an array.

PHP team generator example :

  // only PHP 5.5 function gen_one_to_three () {for ($ i = 1; $ i & lt; = 3; $ i ++) {// Note that $ I is protected between yields yields $ i; }} $ Generator = gen_one_to_three (); Forex currency ($ generator as $ value) {resonant "$ value \ n"; }   

Result :

  1 2 3   

but I can Using the array is the same thing and I can still keep up with previous versions of PHP.

Take a look :

  // Compatible with 4.4.9! Function gen_one_to_three () {$ results = array (); For ($ i = 1; $ i & lt; = 3; $ i ++) {$ Result [] = $ i; } Returns $ results; } $ Generator = gen_one_to_three (); Forex currency ($ generator as $ value) {resonant "$ value \ n"; }   

So the question is : What is the purpose of the existence of this new facility? I need to play all the examples of documentation without using the new feature.

Can someone give a good explanation and perhaps an example which is not necessarily impossible with the older versions, but can the use of generators help in development?

There is a difference in the case of efficiency For example, in many languages ​​other than PHP, two Category function, category () and xrange () are included. This is a very good example of the generator and why use them. Let's build your own:

  function range ($ start, $ end) {$ array = array}; For $ {$ array = $ start; $ i & lt; = $ end; $ i ++} {$ array [] = $ i; } $ Array returned; }   

Now it's actually straight forward. However, for the large range, there is a large amount of memory in it if we try to run it with $ start = 0 and $ end = 100000000 Exit memory!

But if we used a generator:

  function xrange ($ start, $ end) {for ($ i = $ start; $ i & lt; = $ End; $ i ++) {yield $ i; }}   

Now we use continuous memory, yet there is still an "array" (like structure), which we can iterate in one place (and other iterators Can use with).

This does not replace an array , but it provides an efficient way to avoid the need for memory ...

But even more Saving is the generation of items Since each result is prepared as needed, you can delay execution (fetching or computing) of each element until you need it. For example, if you need to fetch one item from one row and make some complex processing in each line, then you can delay with that generator until you actually need that line:

  function fetchFromDb ($ result) {while ($ row = $ result-> fetchArray ()) {$ record = doSomeComplexProcessing ($ line); Produce $ record; }}   

So if you only need the first 3 results, then you will only process the first three records

For more information, The subject was written on.

No comments:

Post a Comment