Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- use Illuminate\Support\Collection;
- // Include Laravel's autoload if you're running this outside a Laravel application
- require 'vendor/autoload.php';
- // Function to measure execution time
- function measureTime(callable $callback)
- {
- $start = microtime(true);
- $callback();
- return microtime(true) - $start;
- }
- // Generate a large dataset of random numbers
- $size = 1000000;
- $data = array_map(fn() => rand(1, 100), range(1, $size));
- // Measure time for PHP array sum
- $arraySumTime = measureTime(function () use ($data) {
- $sum = array_sum($data);
- });
- // Measure time for Laravel Collection sum
- $collectionSumTime = measureTime(function () use ($data) {
- $collection = collect($data);
- $sum = $collection->sum();
- });
- // Measure time for iterating using foreach on PHP array
- $arrayIterationTime = measureTime(function () use ($data) {
- foreach ($data as $value) {
- $temp = $value * 2; // Some simple operation
- }
- });
- // Measure time for iterating using each() on Laravel Collection
- $collectionIterationTime = measureTime(function () use ($data) {
- collect($data)->each(function ($value) {
- $temp = $value * 2; // Some simple operation
- });
- });
- // Display results
- echo "PHP Array Sum Time: {$arraySumTime} seconds\n";
- echo "Laravel Collection Sum Time: {$collectionSumTime} seconds\n";
- echo "PHP Array Iteration Time (foreach): {$arrayIterationTime} seconds\n";
- echo "Laravel Collection Iteration Time (each()): {$collectionIterationTime} seconds\n";
- // Compare performance
- echo "\nPerformance Summary:\n";
- echo "Faster sum operation: " . ($arraySumTime < $collectionSumTime ? "PHP Array" : "Laravel Collection") . "\n";
- echo "Faster iteration operation: " . ($arrayIterationTime < $collectionIterationTime ? "PHP Array" : "Laravel Collection") . "\n";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement