Guest User

generators

a guest
Aug 12th, 2013
306
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function getLines($file) {
  2.     $f = fopen($file, 'r');
  3.     if (!$f) throw new Exception();
  4.     while ($line = fgets($f, 1024)) {          
  5.         yield strlen($line);
  6.     }
  7.     var_dump($f);
  8.     fclose($f);
  9.     var_dump($f);
  10. }
  11.  
  12. function getLines_res($f) {
  13.     if (!$f) throw new Exception();
  14.     while ($line = fgets($f, 1024)) {          
  15.         yield strlen($line);
  16.     }
  17. }
  18.  
  19. function getLines_try($file) {
  20.     $f = fopen($file, 'r');
  21.     if (!$f) throw new Exception();
  22.     try {
  23.       while ($line = fgets($f, 1024)) {    
  24.         yield strlen($line);
  25.       }
  26.     } catch (Exception $e) {
  27.       var_dump($f);
  28.       fclose($f);
  29.       var_dump($f);
  30.     }    
  31.     var_dump($f);
  32.     fclose($f);
  33.     var_dump($f);
  34. }
  35.  
  36.  
  37.  
  38. echo "<pre>";
  39. @Timer::start();
  40. foreach(getLines('xml.xml') as $k => $item){
  41.     echo $k.': '.$item."\n";
  42.     if($k>5){
  43.         echo "break\n";
  44.         break;
  45.     }
  46. }
  47. echo 'Time: '.@Timer::get();
  48.  
  49. echo PHP_EOL.PHP_EOL;
  50.  
  51. @Timer::start();
  52. $f = fopen('xml.xml', 'r');
  53. foreach(getLines_res($f) as $k => $item){
  54.     echo $k.': '.$item."\n";
  55.     if($k>5){
  56.         echo "break\n";
  57.     fclose($f);
  58.         break;
  59.     }
  60. }
  61. echo 'Time: '.@Timer::get();
  62.  
  63.  
  64. echo PHP_EOL.PHP_EOL;
  65.  
  66. @Timer::start();
  67. $gen = getLines_try('xml.xml');
  68. foreach($gen as $k => $item){
  69.     echo $k.': '.$item."\n";
  70.     if($k>5){
  71.         echo "break\n";
  72.     $gen->throw(new Exception('break and close!'));
  73.         break;
  74.     }
  75. }
  76. echo 'Time: '.@Timer::get();
  77.  
  78. echo "</pre>";
RAW Paste Data