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;
- }
- // Define dataset size
- $size = 1000000;
- // Generate the dataset first (NOT included in timing)
- $rawData = range(1, $size);
- shuffle($rawData); // Mix the values randomly
- // Measure time to create the PHP array
- $arrayCreationTime = measureTime(function () use ($rawData, &$data) {
- $data = $rawData; // Simple assignment
- });
- // Measure time to create the Laravel collection
- $collectionCreationTime = measureTime(function () use ($data, &$collection) {
- $collection = collect($data);
- });
- // 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 ($collection) {
- $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 ($collection) {
- $collection->each(function ($value) {
- $temp = $value * 2; // Some simple operation
- });
- });
- // Display results with formatted output (no scientific notation)
- echo "PHP Array Creation Time: " . number_format($arrayCreationTime, 8) . " seconds\n";
- echo "Laravel Collection Creation Time: " . number_format($collectionCreationTime, 8) . " seconds\n";
- echo "PHP Array Sum Time: " . number_format($arraySumTime, 8) . " seconds\n";
- echo "Laravel Collection Sum Time: " . number_format($collectionSumTime, 8) . " seconds\n";
- echo "PHP Array Iteration Time (foreach): " . number_format($arrayIterationTime, 8) . " seconds\n";
- echo "Laravel Collection Iteration Time (each()): " . number_format($collectionIterationTime, 8) . " seconds\n";
- // Compare performance
- echo "\nPerformance Summary:\n";
- echo "Faster data structure creation: " . ($arrayCreationTime < $collectionCreationTime ? "PHP Array" : "Laravel Collection") . "\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