1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* This file is part of library-template |
4
|
|
|
* |
5
|
|
|
* For the full copyright and license information, please view the LICENSE |
6
|
|
|
* file that was distributed with this source code. |
7
|
|
|
* |
8
|
|
|
* @author Nicolò Martini <[email protected]> |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* This is a basic benchmark test for NestedKeyIterator... it's 3 times faster to a |
13
|
|
|
* without-iterator version! (a naive version, though) |
14
|
|
|
*/ |
15
|
|
|
include '../vendor/autoload.php'; |
16
|
|
|
|
17
|
|
|
$ary = array( |
18
|
|
|
'a' => 'b', |
19
|
|
|
'c' => 'd', |
20
|
|
|
'e' => array('f' => 'g', 'h' => 'i', 'l' => array('m', 'n', 'o' => 'p')) |
21
|
|
|
); |
22
|
|
|
|
23
|
|
|
$iterator = new \StringTemplate\NestedKeyIterator(new \RecursiveArrayIterator($ary)); |
24
|
|
|
|
25
|
|
|
$iterateWithIterator = function (&$ary) use ($iterator) { |
|
|
|
|
26
|
|
|
foreach ($iterator as $key => $value) { |
27
|
|
|
$i = $key . $value; |
|
|
|
|
28
|
|
|
} |
29
|
|
|
}; |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* This could be optimized. |
33
|
|
|
* @param $ary |
34
|
|
|
* @param array $keyStack |
35
|
|
|
*/ |
36
|
|
|
$iterateWithoutIterator |
37
|
|
|
= function (&$ary, $keyStack = array()) |
38
|
|
|
{ |
39
|
|
|
global $iterateWithoutIterator; |
40
|
|
|
$keyValues = array(); |
41
|
|
|
foreach ($ary as $key => $value) { |
42
|
|
|
if (!is_array($value)) { |
43
|
|
|
$nestedKey = implode('.', array_merge($keyStack, array($key))); |
44
|
|
|
$keyValues[$nestedKey] = $value; |
45
|
|
|
} else { |
46
|
|
|
$keyStack2 = $keyStack; |
47
|
|
|
$keyStack2[] = $key; |
48
|
|
|
$keyValues = array_merge($keyValues, $iterateWithoutIterator($value, $keyStack2)); |
49
|
|
|
} |
50
|
|
|
} |
51
|
|
|
}; |
52
|
|
|
|
53
|
|
|
function benchmark($f, $ary, $title = '', $iterations = 10000 ) |
|
|
|
|
54
|
|
|
{ |
55
|
|
|
echo '<br><b>', $title, '</b><br>'; |
56
|
|
|
$start = microtime(true); |
57
|
|
|
for ($i = 0; $i < $iterations; $i++) |
58
|
|
|
$f($ary); |
59
|
|
|
$time = microtime(true) - $start; |
60
|
|
|
echo 'Time: ', $time, '<br>'; |
61
|
|
|
echo 'Average: ', $time / $iterations, '<br>'; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
benchmark($iterateWithIterator, $ary, 'With Iterator'); |
|
|
|
|
65
|
|
|
benchmark($iterateWithoutIterator, $ary, 'Without Iterator'); |
|
|
|
|
This check looks from parameters that have been defined for a function or method, but which are not used in the method body.