gists/php/string-count-test.php

44 lines
1.2 KiB
PHP
Raw Normal View History

2022-01-11 00:52:00 +00:00
<?php
// Simple substring search benchmark
// https://gist.github.com/anthonyaxenov/045dac59676826236319199df1597bb5
$string = str_repeat('1', 100);
$max = 5000;
$results = [
'preg_match_all' => [
'total' => 0,
'avg' => 0
],
'substr_count' => [
'total' => 0,
'avg' => 0
],
'count_chars' => [
'total' => 0,
'avg' => 0
],
];
for ($i = 0; $i < $max; ++$i) {
$start = microtime(true);
preg_match_all('/1/', $string);
$results['preg_match_all']['total'] += round((microtime(true) - $start), 8);
}
$results['preg_match_all']['avg'] = round($results['preg_match_all']['total'] / $max, 8);
for ($i = 0; $i < $max; ++$i) {
$start = microtime(true);
substr_count($string, '1');
$results['substr_count']['total'] += round((microtime(true) - $start), 8);
}
$results['substr_count']['avg'] = round($results['substr_count']['total'] / $max, 8);
for ($i = 0; $i < $max; ++$i) {
$start = microtime(true);
count_chars($string, 1);
$results['count_chars']['total'] += round((microtime(true) - $start), 8);
}
$results['count_chars']['avg'] = round($results['count_chars']['total'] / $max, 8);
print_r($results);