Guest User

Untitled

a guest
Apr 11th, 2012
60
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2.  
  3. include 'inc/config.php';
  4.  
  5. # замер времени
  6. function timeMeasure()
  7. {
  8.     list( $msec, $sec ) = explode( chr(32), microtime() );
  9.     return $sec + $msec;
  10. }
  11.  
  12. # вывод результатов
  13. function timeMeasureEnd( $label )
  14. {
  15.     echo '<p>result ['.$label.'] = '.round( timeMeasure() - constant( $label ), 4 ).'</p>';
  16. }
  17.  
  18. # генерируем массив
  19. define( 'GENERATE_ARRAY', timeMeasure() );
  20. $ar = array();
  21. for( $i = 0; $i < 100000; ++ $i )
  22. {
  23.     $ar[] = 1;
  24. }
  25. timeMeasureEnd( 'GENERATE_ARRAY' );
  26.  
  27. # используем указатели
  28. define( 'FOREACH_WITH_POINTER', timeMeasure() );
  29. foreach( $ar as &$value )
  30. {
  31.     ++ $value;
  32. }
  33. timeMeasureEnd( 'FOREACH_WITH_POINTER' );
  34.  
  35. # используем ключи массива
  36. define( 'FOREACH_WITHOUT_POINTER', timeMeasure() );
  37. foreach( $ar as $key => $value )
  38. {
  39.     $ar[ $key ] = $value + 1;
  40. }
  41. timeMeasureEnd( 'FOREACH_WITHOUT_POINTER' );
  42.  
  43. # работаем с другим массивом
  44. define( 'FOREACH_WITH_REPLACE', timeMeasure() );
  45. foreach( $ar as $value )
  46. {
  47.     $new_ar[] = $value + 1;
  48. }
  49. $ar = $new_ar;
  50. timeMeasureEnd( 'FOREACH_WITH_REPLACE' );
  51.  
  52. # используем array_map
  53. define( 'ARRAY_MAP', timeMeasure() );
  54. function test( $value ){ return $value + 1; };
  55. $ar = array_map( 'test', $ar );
  56. timeMeasureEnd( 'ARRAY_MAP' );
  57.  
  58. ?>
  59.  
  60. result [GENERATE_ARRAY] = 0.0376
  61. result [FOREACH_WITH_POINTER] = 0.0099
  62. result [FOREACH_WITHOUT_POINTER] = 0.0576
  63. result [FOREACH_WITH_REPLACE] = 0.0509
  64. result [ARRAY_MAP] = 0.0867
RAW Paste Data