PHP

What is faster NULL or Exception? (on PHP)

<?php

$count = 100000;

$start_time = microtime(true);
for ($i = 1; $i < $count; $i++)
{
	$num = random_int(20, 1000);
	try
	{
		echo checkNum($num);
	} catch (Exception $e)
	{
		continue;
	}
}
$end_time = microtime(true);
$execution_time = ($end_time - $start_time);

function checkNum($num): string
{
	if ($num > 10)
	{
		throw new Exception('bla bla');
	}
	else
	{
		return 'ok';
	}
}

echo " Execution time of EXCEPTION script = " . $execution_time . " sec" . PHP_EOL;


$start_time = microtime(true);
for ($i = 1; $i < $count; $i++)
{
	$num = random_int(20, 1000);

	$WTF = checkNumOrReturnNull($num);

	if ($WTF != null)
	{
		echo 'ok';
	}
}
$end_time = microtime(true);
$execution_time = ($end_time - $start_time);

function checkNumOrReturnNull($num)
{
	if ($num > 10)
	{
		return null;
	}

	return 'ok';
}

echo " Execution time of NULL script = " . $execution_time . " sec" . PHP_EOL;

 

Result:

 Execution time of EXCEPTION script = 0.2258 sec
 Execution time of NULL script = 0.1651 sec

 

 

 

Афоризм дня:
Многочисленность фактов и сочинений растет так быстро, что в недалеком будущем придется сводить все к извлечениям и словарям. (547)

Leave a reply

Яндекс.Метрика