-
Notifications
You must be signed in to change notification settings - Fork 0
/
str_replace_vs_strtr.php
62 lines (55 loc) · 1.73 KB
/
str_replace_vs_strtr.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<?php
#error_reporting (0);
class perf {
private $times = [];
private $start = null;
public function start() {
$this->start = microtime(true);
}
public function stop(string $label) {
$this->times[$label] = microtime(true) - $this->start;
}
public function report() {
asort($this->times, SORT_NUMERIC);
$bench = current($this->times);
foreach($this->times as $label => $time) {
$time = number_format($time, 5);
echo sprintf("%s%% %ss %s\n", number_format(bcmul(bcdiv($time,$bench,10),100, 10),1), $time, $label);
}
}
}
$p = new perf();
$x = new class() { public $y = []; };
$array = ['x'=>'y', 'y'=>'z', 'z'=>'a', 'a'=>'Z'];
$value = 'abcxyzabcxyzabcxyzabcxyzabcxyzabcxyzabcxyzabcxyzabcxyzabcxyz';
$p->start();
for($i=10000;$i;$i--) {
str_replace(array_keys($array), array_values($array), $value);
}
$p->stop('str_replace()');
echo "str_replace:\n",str_replace(array_keys($array), array_values($array), $value), "\n";
$p->start();
for($i=10000;$i;$i--) {
strtr($value, $array);
}
$p->stop('strtr()');
echo "strtr:\n",strtr($value, $array), "\n";
$p->report();
$p = new perf();
$x = new class() { public $y = []; };
// key-value with different order
$array = ['a'=>'Z','x'=>'y', 'y'=>'z', 'z'=>'a' ];
$value = 'abcxyzabcxyzabcxyzabcxyzabcxyzabcxyzabcxyzabcxyzabcxyzabcxyz';
$p->start();
for($i=10000;$i;$i--) {
str_replace(array_keys($array), array_values($array), $value);
}
$p->stop('str_replace()');
echo "str_replace:\n",str_replace(array_keys($array), array_values($array), $value), "\n";
$p->start();
for($i=10000;$i;$i--) {
strtr($value, $array);
}
$p->stop('strtr()');
echo "strtr:\n",strtr($value, $array), "\n";
$p->report();