Benchmarking
Learn to write benchmarks that compare code pieces with microtime().
Benchmark with microtime(true)
microtime(true) returns the current time as a fractional number of seconds. To time a piece of code you call it before and after and subtract: $start = microtime(true); … $end = microtime(true); $elapsed = $end - $start;.
Microsecond precision lets you compare even very short snippets. The result depends on the machine and the load, so averaging several runs is safer than a single shot. Rather than printing the raw measurement, run two approaches under the same conditions and compare counts for a deterministic answer.
echo, foreach and str_replace choices
Different methods that do the same job have different costs. echo is faster than printf for a single string because there is no formatting step; but printf reads better when you interpolate variables.
foreach is usually faster than a for loop with an index because PHP carries the array pointer internally. array_map calls a function per element, so it is slower than a loop but more declarative.
str_replace and strtr do the same job: strtr applies all replacements in a single pass, str_replace can apply them sequentially; on short strings strtr is usually faster. These gaps matter on large data.
Exercise Compare isset, array_search, str_replace and strtr
Start with $start = microtime(true). Look up 'cherry' in $data with isset, assign to $found_isset. Find value 3 with array_search in strict mode, assign to $key. Transform 'abab' with a→X, b→Y using str_replace, assign to $out1. Do the same transform with strtr, assign to $out2. Compute $end = microtime(true) and $elapsed = $end - $start. Print $found_isset ? 1 : 0 with printf. Print $key, $out1, $out2, count($data) with echo.
Show example solution
0); echo $key . "\n"; echo $out1 . "\n"; echo $out2 . "\n"; echo count($data) . "\n";.
Example solution:
<?php
$start = microtime(true);
$data = ['apple' => 1, 'pear' => 2, 'cherry' => 3];
$found_isset = isset($data['cherry']);
$key = array_search(3, $data, true);
$out1 = str_replace(['a', 'b'], ['X', 'Y'], 'abab');
$out2 = strtr('abab', ['a' => 'X', 'b' => 'Y']);
$end = microtime(true);
$elapsed = $end - $start;
printf("%d\n", $found_isset ? 1 : 0);
echo $key . "\n";
echo $out1 . "\n";
echo $out2 . "\n";
echo count($data) . "\n";
Test yourself
-
Compare isset and array_search
- array_search is faster than isset
- Both are equally fast
- isset only works on numeric arrays
- isset is O(1), array_search is O(n), so isset is faster
Show answer
isset is O(1), array_search is O(n), so isset is faster — Correct. isset does a hash lookup (O(1)); array_search scans linearly (O(n)).
-
Complete the $start assignment
____ = microtime(true); // code here $end = microtime(true);Show answer
$start = microtime(true); // code here $end = microtime(true); -
Match the benchmark methods
- microtime(true)
- Time measure
- isset
- O(1) array lookup
- array_search
- O(n) array lookup
- strtr
- Single-pass replace