Question: Should you check for a file before attempting to include it, or just suppress errors? Calling file_exists
requires stat
ing it twice if the file does exist, so that could take longer. Answer: the file_exists
pattern is more than five times faster than the @include
pattern for a file that doesn’t exist, and not substantially slower when the file does exist.
The test:
<?php
$start_time = $end_time = $i = 0;
$start_time = microtime( TRUE );
for( $i = 0; $i <= 100000; $i++)
{
include __DIR__ . '/config.php';
}
$end_time = microtime( TRUE );
echo 'Test 1: '. ( $end_time - $start_time ) ." seconds \n\n";
//Test 1: 13.27784204483 seconds
$start_time = microtime( TRUE );
for( $i = 0; $i <= 100000; $i++)
{
@include __DIR__ . '/config.php';
}
$end_time = microtime( TRUE );
echo 'Test 2: '. ( $end_time - $start_time ) ." seconds \n\n";
//Test 2: 13.47793507576 seconds
$start_time = microtime( TRUE );
for( $i = 0; $i <= 100000; $i++)
{
@include __DIR__ . '/nonexistant-file.php';
}
$end_time = microtime( TRUE );
echo 'Test 3: '. ( $end_time - $start_time ) ." seconds \n\n";
// Test 3: 3.8437511920929 seconds
$start_time = microtime( TRUE );
for( $i = 0; $i <= 100000; $i++)
{
if( file_exists( __DIR__ . '/config.php' ) )
{
include __DIR__ . '/config.php';
}
}
$end_time = microtime( TRUE );
echo 'Test 4: '. ( $end_time - $start_time ) ." seconds \n\n";
// Test 4: 14.759271144867 seconds
$start_time = microtime( TRUE );
for( $i = 0; $i <= 100000; $i++)
{
if( file_exists( __DIR__ . '/nonexistant-file.php' ) )
{
include __DIR__ . '/nonexistant-file.php';
}
}
$end_time = microtime( TRUE );
echo 'Test 5: '. ( $end_time - $start_time ) ." seconds \n\n";
// Test 5: 0.74464702606201 seconds