Domanda

I'm coding a multi language website. The text for each page is loaded from a MySQL database and should be assigned to an array or constant to insert it into the web content.

I would like to know if it is better, to save memory and for best performance, the use of constants or arrays to store the text. i.e.

foreach ($db_text_object as $t){
  $text["$t->key"] = $t->text;
}

or:

foreach ($db_text_object as $t){
  define($t->key, $t->text);
}

To be used as:

echo $text['mytext'];

or:

echo mytext;

Any other comment about advantage or disadvantage of each method will be appreciated.

Thank you.

È stato utile?

Soluzione 2

The performance difference will be too trivial or too minute

I personally go with the arrays, since you would be able to access it in a simpler way..

Benchmarking results...

<?php


$db_text_object=[1,2,3,4,5];
$start = microtime(true);
foreach ($db_text_object as $k=>$v){
    $text[$k] = $v;
}
echo "Constant Performance: " . (microtime(true) - $start) . "\n";

$start = microtime(true);
foreach ($db_text_object as $k=>$v){
    define($k, $v);
}
echo "Array Performance: " . (microtime(true) - $start) . "\n";

OUTPUT:

Constant Performance: 1.9073486328125E-5 
Array Performance: 1.3113021850586E-5

Benchmarking Demo at CodeViper

Altri suggerimenti

I don't think either will have a significant impact on performance, especially since the bottleneck will be getting all the data from the database every single time. If you're really interested in whether it makes a difference: try it both ways and measure it.

When you're done doing that, do it right by using a native extension like gettext, which was made for this exact purpose, does internal caching of binary translation files and comes with a whole ecosystem of tools supporting the translation workflow.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top