Comparative analysis of yield iterator implementation methods between php and C

  • 2021-12-13 07:38:43
  • OfStack

In this paper, the implementation method of yield iterator between php and C # is compared with an example. Share it for your reference, as follows:

The yield keyword is used to facilitate the implementation of iterators, eliminating the tedious task of writing iterators manually. Iterators are often used to implement coroutines, so most coroutines have the yield keyword. See the coroutines of unity3D.

C # Version:

The return type of the function must be IEnumerable, IEnumerable < T > , IEnumerator or IEnumerator < T > .

IEnumerable means that a class can be iterated, that is, it can be traversed with foreach, IEnumerator is the real iterator implementation, IEnumerable and IEnumerator1 are interfaces that use iterators, and one is an interface that implements iterators.

How does C # implement an iterator with yield? In fact, the compiler generates internal classes according to yield keywords, which can be seen under decompilation 1.


using System.Collections;
class Program
{
   // Return IEnumerable Interface, which actually returns the internal class generated by the compiler 
  public static IEnumerable fib(int n)
  {
    int cur = 1;
    int prev = 0;
    for (int i = 0; i < n; i++)
    {
      yield return cur;
      int temp = cur;
      cur = prev + cur;
      prev = temp;
    }
  }
  static void Main()
  {
    // Display powers of 2 up to the exponent 8:
    foreach (int i in fib(9))
    {
      Console.Write("{0} ", i);
    }
  }
}
// prints: 1 1 2 3 5 8 13 21 34

php version:

The function returns the class Generator, which implements the iterator interface Iterator.


<?php
// Return Iterator Interface, php The interpreter helped us return Generator Class 
function fib($n)
{
  $cur = 1;
  $prev = 0;
  for ($i = 0; $i < $n; $i++) {
    yield $cur;
    $temp = $cur;
    $cur = $prev + $cur;
    $prev = $temp;
  }
}
$fibs = fib(9);
foreach ($fibs as $fib) {
  echo " " . $fib;
}
// prints: 1 1 2 3 5 8 13 21 34

For more readers interested in PHP related content, please check the topics on this site: "Introduction to php Object-Oriented Programming", "Encyclopedia of PHP Array (Array) Operation Skills", "Introduction to PHP Basic Syntax", "Summary of PHP Operation and Operator Usage", "Summary of php String (string) Usage", "Introduction to php+mysql Database Operation" and "Summary of php Common Database Operation Skills"

I hope this article is helpful to everyone's PHP programming.


Related articles: