Skip to content

Commit 5f093c9

Browse files
committed
add string reverse test
1 parent e83ca23 commit 5f093c9

File tree

4 files changed

+59
-0
lines changed

4 files changed

+59
-0
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
.idea

str-reverse/array.php

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
<?php
2+
list($script, $option, $n) = $argv;
3+
$s = microtime(true);
4+
5+
function dispatch($str) {
6+
return implode(array_reverse(mb_str_split($str)));
7+
}
8+
9+
$range = range(1, $n ?? 1);
10+
foreach ($range as $i) {
11+
dispatch($option);
12+
}
13+
14+
echo ( microtime(true) - $s) * 1000;

str-reverse/readme.md

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
A not-so-scientific `implode > array_reverse > mb_str_split` vs `for loop with mb_substr` speed test.
2+
3+
Run Commands:
4+
5+
```
6+
// args: string "starting with a", "num times to run"
7+
php substr.php abcd 10000
8+
php array.php abcd 10000
9+
```
10+
11+
### Huge Set ~1_000_000 calls
12+
13+
- *Array*: `401.384ms`
14+
- *SubStr*: `999.577ms`
15+
16+
### Large Set ~10000 calls
17+
18+
- *Array*: `5.398ms`
19+
- *SubStr*: `12.624ms`
20+
21+
### Small Set ~100 calls
22+
23+
- *Array*: `0.070ms`
24+
- *SubStr*: `0.147ms`
25+
26+
My conclusion is that `implode >array_reverse > mb_str_split` is much better if detecting the first char.

str-reverse/substr.php

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
<?php
2+
list($script, $option, $n) = $argv;
3+
$s = microtime(true);
4+
5+
function dispatch($str) {
6+
$r = '';
7+
for ($i = mb_strlen($str); $i>=0; $i--) {
8+
$r .= mb_substr($str, $i, 1);
9+
}
10+
return $r;
11+
}
12+
13+
$range = range(1, $n ?? 1);
14+
foreach ($range as $i) {
15+
dispatch($option);
16+
}
17+
18+
echo ( microtime(true) - $s) * 1000;

0 commit comments

Comments
 (0)