Skip to content

Instantly share code, notes, and snippets.

@pierredup
Created October 15, 2014 15:51
Show Gist options
  • Save pierredup/d0e5e6b6039a771ad3eb to your computer and use it in GitHub Desktop.
Save pierredup/d0e5e6b6039a771ad3eb to your computer and use it in GitHub Desktop.
SplMinHeap and SplMaxHeap Benchmark
<?php
// Generate random numbers
// Assume this is our info that we get from a CSV file or somewhere else
$collection = array();
for ($i = 0; $i < 1000000; $i++) {
$collection[] = rand(1, 1000000);
}
// Benchmark array_walk() with SplMinHeap
$time_start = microtime(true);
$heap = new SplMinHeap;
array_walk($collection, function($item) use ($heap) {
$heap->insert($item);
}, $collection);
$current = $heap->current();
$time_end = microtime(true);
$time = $time_end - $time_start;
var_dump($time);
reset($collection);
// Benchmark foreach with SplMinHeap
$time_start = microtime(true);
$heap = new SplMinHeap;
foreach ($collection as $item) {
$heap->insert($item);
}
$current = $heap->current();
$time_end = microtime(true);
$time = $time_end - $time_start;
var_dump($time);
reset($collection);
// Benchmark foreach with temporary array
$time_start = microtime(true);
$array = array();
foreach($collection as $item) {
$array[] = $item;
}
$current = min($array);
$time_end = microtime(true);
$time = $time_end - $time_start;
var_dump($time);
double(5.2539360523224)
double(1.4025628566742)
double(0.26065611839294)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment