<commit_before><commit_msg>- Initial release<commit_after><?php
/* This file is part of the XP framework's experiments
 *
 * $Id$ 
 */
  require('lang.base.php');
  xp::sapi('cli');
  uses('util.profiling.Timer');

  // {{{ ElseIfStrategy
  class ElseIfStrategy extends Object {
  
    function run($times) {
      $two= $three= $four= $else= 0;
      for ($i= 0; $i < $times; $i++) {
        if ($i % 2 == 0) {
          $two++;
        } elseif ($i % 3 == 0) {
          $three++;
        } elseif ($i % 4 == 0) {
          $four++;
        } else {
          $else++;
        }
      }
    }
  }
  // }}}

  // {{{ ElseStrategy
  class ElseStrategy extends Object {
  
    function run($times) {
      $two= $three= $four= $else= 0;
      for ($i= 0; $i < $times; $i++) {
        if ($i % 2 == 0) {
          $two++;
        } elseif ($i % 3 == 0) {
          $three++;
        } elseif ($i % 4 == 0) {
          $four++;
        } else {
          $else++;
        }
      }
    }
  }
  // }}}

  // {{{ SwitchStrategy
  class SwitchStrategy extends Object {
  
    function run($times) {
      $two= $three= $four= $else= 0;
      for ($i= 0; $i < $times; $i++) {
        switch (TRUE) {
          case $i % 2 == 0: $two++; break;
          case $i % 3 == 0: $three++; break;
          case $i % 4 == 0: $four++; break;
          default: $else++; break;
        }
      }
    }
  }
  // }}}

  // {{{ main
  $p= &new ParamString();
  
  // Display help
  if ($p->exists('help', '?') || !$p->exists(1)) {
    Console::writeLinef(<<<__
Tests performance of switch vs. elseif vs. else if.

Usage:
$ php elseif.php <strategy> [-t times]
  
  * strategy is one of "elseif", "else", "switch"
  
  * times specifies how often to call the function and defaults to 100.000
__
    );
    exit(1);
  }
  
  try(); {
    $class= &XPClass::forName(ucfirst($p->value(1)).'Strategy');
    $class && $strategy= &$class->newInstance();
  } if (catch('ClassNotFoundException', $e)) {
    $e->printStackTrace();
    exit(-1);
  }
 
  $times= $p->value('times', 't', 100000);
  $t= &new Timer();
  $t->start(); {
    $strategy->run($times);
  } $t->stop();
  
  Console::writeLinef(
    '%s: %.3f seconds for %d calls', 
    $strategy->getClassName(), 
    $t->elapsedTime(), 
    $times
  );
  // }}}
?>

{'fraction_non_alphanumeric': 0.2099519860323003, 'fraction_numerical': 0.01789611523352248, 'mean_word_length': 1.9049429657794676, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 16, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1078339', 'n_tokens_mistral': 864, 'n_tokens_neox': 814, 'n_words': 203}