PHP Benchmarks

Performance comparison of PHP code alternatives.

Test: if vs. switch

No Description

Run this test again Return to test menu

Historical Results

Based on (1) saved test runs, The test labeled "if elseif else" was (on average) the faster by 0.0096 seconds, (1.821% faster)

if elseif else 100%
switch 98.179%

The if elseif else test took 0.5151 seconds.
The switch test took 0.5247 seconds.

Nitty-Gritty

Each test case ran 20 random code order iterations consisting of 136,577 loops for a total of 2,731,540 runs.

  • Line execution difference (0.000003) milliseconds.
  • Avg difference (0.000) milliseconds per 136,577 loops.
  • Total difference 9.56 milliseconds for 2,731,540 loops

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

Code

The first test, "if elseif else", was:

foreach ($GLOBALS['dummy'] as $v)
{
	if ($v == 2)
		$GLOBALS['dummy2'] = 1;
	elseif ($v == 5)
		$GLOBALS['dummy2'] = 2;
	elseif ($v == 1)
		$GLOBALS['dummy2'] = 3;
	elseif ($v == 3)
		$GLOBALS['dummy2'] = 4;
	elseif ($v == 0)
		$GLOBALS['dummy2'] = 5;
	else
		$GLOBALS['dummy2'] = 6;
}

The second test, "switch", was:

foreach ($GLOBALS['dummy'] as $v)
{
	switch ($v)
	{
	case 2:
		$GLOBALS['dummy2'] = 1;
		break;

	case 5:
		$GLOBALS['dummy2'] = 2;
		break;

	case 1:
		$GLOBALS['dummy2'] = 3;
		break;

	case 3:
		$GLOBALS['dummy2'] = 4;
		break;

	case 0:
		$GLOBALS['dummy2'] = 5;
		break;

	default:
		$GLOBALS['dummy2'] = 6;
	}
}

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