Bueno, pues me decidí a hacer un pequeño script para ver qué opción era más rápida y, para mi sorpresa, los arrays son mucho más rápidos de acceder que las constantes. Aquí el script:
Código PHP:
// test
$n = isset($_GET['n']) ? $_GET['n'] : 1000;
$decimals = 6;
$key_prefix = 'CONST_';
$test_file = 'test_const.php';
// create content of test file
for( $index = 1; $index <= $n; $index++ )
{
$const[] = "define('".$key_prefix.$index."', '$index');";
$const_check[] = "\$var = ".$key_prefix.$index.";";
$var[] = "\$array['".$key_prefix.$index."'] = $index;";
$var_check[] = "\$var = \$array['".$key_prefix.$index."'];";
}
// write into file
$handle = @fopen($test_file, "w");
$new_line = "\r\n";
fwrite($handle, "<?php $new_line$new_line");
fwrite($handle, "$new_line echo "Number of elements (constants/vars): $n<br />\";");
fwrite($handle, "$new_line \$start_memory = memory_get_usage();$new_line");
fwrite($handle, implode('', $const));
fwrite($handle, "$new_line \$used_memory_const = (memory_get_usage() - \$start_memory);$new_line");
fwrite($handle, "$new_line \$start_time = microtime();$new_line");
fwrite($handle, implode('', $const_check));
fwrite($handle, "$new_line \$time_defines = microtime() - \$start_time; $new_line");
fwrite($handle, "$new_line echo \"<br />With defines: \";");
fwrite($handle, "$new_line echo number_format(\$time_defines, $decimals).\" sec. and \".\$used_memory_const.\" used memory.\";");
fwrite($handle, "$new_line \$start_memory = memory_get_usage();$new_line");
fwrite($handle, implode('', $var));
fwrite($handle, "$new_line \$used_memory_vars = (memory_get_usage() - \$start_memory);$new_line");
fwrite($handle, "$new_line \$start_time = microtime();$new_line");
fwrite($handle, implode('', $var_check));
fwrite($handle, "$new_line \$time_vars = microtime() - \$start_time;");
fwrite($handle, "$new_line echo \"<br />With vars: \";");
fwrite($handle, "$new_line echo number_format(\$time_vars, $decimals).\" sec. and \".\$used_memory_vars.\" used memory.\";");
fwrite($handle, "$new_line echo \"<br /><br />Constants vs. Variables: \";");
fwrite($handle, "$new_line echo \"<br />% Time: \".number_format(\$time_defines/\$time_vars*100, 2).\"%\";");
fwrite($handle, "$new_line echo \"<br />% Memory: \".number_format(\$used_memory_const/\$used_memory_vars*100, 2).\"%\";");
fwrite($handle, "$new_line?>");
fclose($handle);
// execute test
include($test_file);
Lo hice de este modo porque creo que no se puede acceder al valor de una constante dinámicamente. Cualquier crítica constructiva será bien recibida.
Un saludo.
EDITADO: He añadido información acerca de la memoria usada. Con variables se utiliza bastante más de memoria (el % usado por constantes es aproximadamente el 20% del usado por variables).