PHP Benchmarks

Performance comparison of PHP code alternatives.

Test: foreach vs. while (next)

Some people say that next() is faster than a foreach. Is it really? Note that this code won't work at all if the array has false values in it.

View test history (1) Run this test again Return to test menu

Result: Discarded

The test labeled "foreach" was the faster by 0.0243 seconds, (3.737% faster)

foreach 100%
while (next) 96.263%

The foreach test took 0.6268 seconds.
The while (next) test took 0.6511 seconds.

Nitty-Gritty

Each test case ran 20 random code order iterations consisting of 147,829 loops for a total of 2,956,580 runs.

  • Line execution difference (0.000008) milliseconds.
  • Avg difference (1.217) milliseconds per 147,829 loops.
  • Total difference 24.33 milliseconds for 2,956,580 loops

The iteration variablity for Code 1 was (3.5426) milliseconds and Code 2 was (3.1826) milliseconds. The lower and the closer together there values are the more accurate the results are.

Code

The first test, "foreach", was:

foreach ($GLOBALS['dummy'] as $v)
	$v[0] + 1;

The second test, "while (next)", was:

reset($GLOBALS['dummy']);
while (($v = next($GLOBALS['dummy'])) !== false)
	$v[0] + 1;

Running: Linux (x86_64:1 GB) PHP (7.2.25-1+ubuntu16.04.1+deb.sury.org+1)