Skip to content

Instantly share code, notes, and snippets.

@ksimka
Created September 11, 2014 09:10
Show Gist options
  • Save ksimka/6a39496dd8db95a904b7 to your computer and use it in GitHub Desktop.
Save ksimka/6a39496dd8db95a904b7 to your computer and use it in GitHub Desktop.
explode vs sscanf benchmark
<?php
// Test for one case: exploding string by space to two parts
function rand_str() {
return substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, rand(10, 20));
}
$strs = [];
for ($i = 0; $i < 100000; $i++) {
$strs[] = rand_str() . ' ' . rand_str();
}
function list_explode($str) {
list($a, $b) = explode(' ', $str, 2);
return [$a, $b];
}
function list_sscanf($str) {
list($a, $b) = sscanf($str, '%s %s');
return [$a, $b];
}
function sscanf_var($str) {
$a = $b = '';
sscanf($str, '%s %s', $a, $b);
return [$a, $b];
}
function test() {
$s = 'abc xyz';
$r = ['abc', 'xyz'];
if ($r !== list_explode($s)) {
return 'list_explode';
}
if ($r !== list_sscanf($s)) {
return 'list_sscanf';
}
if ($r !== sscanf_var($s)) {
return 'sscanf_var';
}
return '';
}
if ($e = test()) {
die($e);
}
function benchmark($strs, $function) {
$st = microtime(1);
array_walk($strs, $function);
$t = microtime(1) - $st;
return $t;
}
$fs = ['list_explode', 'list_sscanf', 'sscanf_var'];
shuffle($fs);
foreach ($fs as $f) {
echo $f . ': ' . benchmark($strs, $f) . ' ms' . PHP_EOL;
}
// sscanf_var: 0.38089799880981 ms
// list_explode: 0.39630103111267 ms
// list_sscanf: 0.42301893234253 ms
// list_explode: 0.38005208969116 ms
// sscanf_var: 0.38540816307068 ms
// list_sscanf: 0.41617298126221 ms
// sscanf_var: 0.38568210601807 ms
// list_explode: 0.40334486961365 ms
// list_sscanf: 0.43618392944336 ms
// sscanf_var: 0.36920094490051 ms
// list_explode: 0.38223195075989 ms
// list_sscanf: 0.41423678398132 ms
// So, results are (from fastest to slowest)
// 1. sscanf
// 2. list+explode
// 3. list+sscanf
// The same results for exploding to four parts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment