Advertisement
Guest User

Untitled

a guest
Jan 30th, 2025
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.81 KB | Software | 0 0
  1. <?php
  2.  
  3. use Illuminate\Support\Collection;
  4.  
  5. // Include Laravel's autoload if you're running this outside a Laravel application
  6. require 'vendor/autoload.php';
  7.  
  8. // Function to measure execution time
  9. function measureTime(callable $callback)
  10. {
  11.     $start = microtime(true);
  12.     $callback();
  13.     return microtime(true) - $start;
  14. }
  15.  
  16. // Generate a large dataset of random numbers
  17. $size = 1000000;
  18. $data = array_map(fn() => rand(1, 100), range(1, $size));
  19.  
  20. // Measure time for PHP array sum
  21. $arraySumTime = measureTime(function () use ($data) {
  22.     $sum = array_sum($data);
  23. });
  24.  
  25. // Measure time for Laravel Collection sum
  26. $collectionSumTime = measureTime(function () use ($data) {
  27.     $collection = collect($data);
  28.     $sum = $collection->sum();
  29. });
  30.  
  31. // Measure time for iterating using foreach on PHP array
  32. $arrayIterationTime = measureTime(function () use ($data) {
  33.     foreach ($data as $value) {
  34.         $temp = $value * 2; // Some simple operation
  35.     }
  36. });
  37.  
  38. // Measure time for iterating using each() on Laravel Collection
  39. $collectionIterationTime = measureTime(function () use ($data) {
  40.     collect($data)->each(function ($value) {
  41.         $temp = $value * 2; // Some simple operation
  42.     });
  43. });
  44.  
  45. // Display results
  46. echo "PHP Array Sum Time: {$arraySumTime} seconds\n";
  47. echo "Laravel Collection Sum Time: {$collectionSumTime} seconds\n";
  48. echo "PHP Array Iteration Time (foreach): {$arrayIterationTime} seconds\n";
  49. echo "Laravel Collection Iteration Time (each()): {$collectionIterationTime} seconds\n";
  50.  
  51. // Compare performance
  52. echo "\nPerformance Summary:\n";
  53. echo "Faster sum operation: " . ($arraySumTime < $collectionSumTime ? "PHP Array" : "Laravel Collection") . "\n";
  54. echo "Faster iteration operation: " . ($arrayIterationTime < $collectionIterationTime ? "PHP Array" : "Laravel Collection") . "\n";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement