-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcompare_placeholder_replacement.php
90 lines (74 loc) · 2.61 KB
/
compare_placeholder_replacement.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<?php declare(strict_types=1);
require_once __DIR__.'/../vendor/autoload.php';
/*
* You can use an closure or a class that implements TestInterface.
*
* Data that will be processed by the tested function can be executed
* without including its execution time. This will provide more accurate data.
*/
abstract class AbstractBenchmark implements \mre\PHPench\BenchmarkInterface
{
protected $text;
protected $placeholders;
public function setUp($arrSize): void
{
$this->text = $this->createText(10);
$this->placeholders = $this->createPlaceholders($arrSize);
}
protected function createText($n)
{
$text = 'Lorem Ipsum Text ';
for ($i = 0; $i < $n; $i++) {
$text .= ' placeholder: $placeholder_' . $i;
}
return $text;
}
protected function createPlaceholders($n)
{
$placeholders = [];
for ($i = 0; $i < $n; $i++) {
$placeholders['$placeholder_' . $i] = $i;
}
return $placeholders;
}
}
class BenchmarkStringReplaceForeach extends AbstractBenchmark
{
public function execute(): void
{
foreach ($this->placeholders as $search => $replace) {
$this->text = str_replace($search, $replace, $this->text);
}
}
}
class BenchmarkStringReplaceArrayValue extends AbstractBenchmark
{
public function execute(): void
{
$this->text = str_replace(array_keys($this->placeholders), array_values($this->placeholders), $this->text);
}
}
class BenchmarkPregReplaceCallback extends AbstractBenchmark
{
public function execute(): void
{
$this->text = preg_replace_callback('/(\$[\w\d]+)\s/', function ($matches) {
return isset($this->placeholders[$matches[0]]) ? $this->placeholders[$matches[0]] : $matches[0];
}, $this->text);
}
}
// Create a new benchmark instance
$phpench = new mre\PHPench(new \mre\PHPench\Aggregator\MedianAggregator());
$output = new \mre\PHPench\Output\GnuPlotOutput('test3.png', 1024, 768);
$output->setTitle('Compare placeholder replacement');
$phpench->setOutput($output);
// Add your test to the instance
$phpench->addBenchmark(new BenchmarkStringReplaceForeach(), 'TestStringReplaceForeach');
$phpench->addBenchmark(new BenchmarkStringReplaceArrayValue(), 'TestStringReplaceArrayValue');
$phpench->addBenchmark(new BenchmarkPregReplaceCallback(), 'TestPregReplaceCallback');
// Run the benchmark and plot the results in realtime.
// With the second parameter you can specify
// the start, end and step for each call
$phpench->setInput(range(0, 200, 2));
$phpench->setRepetitions(10);
$phpench->run();