Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can defining a lot of constants cause performance or memory problems?

I have a website which uses a lot of constants, that are defined like this, for example:

define('CONSTANT', 1)

I currently have a list of about 200 defines like this. This list is run every time a page loads. Is this going to affect my performance or memory use badly?

like image 814
KnowsLittle Avatar asked Aug 15 '11 06:08

KnowsLittle


People also ask

Do constants take up memory?

Constants can still use RAM. The complier may put the constant into RAM and then reference that constant throughout the code. They keyword const still consumes RAM. The word "const" only tells the complier that the code can't change the value.

Do constants use less memory?

No a constant uses the exact same memory. The only difference is that you can't change your constant after it's initialized.


2 Answers

There are reasons to avoid a list of 200 constants on every page load, but performance and memory usage would not be among them. In general, the best way to answer these kinds of questions is to run benchmarks. Measure page load time and memory usage both with and without loading your 200 constants. Measure a few thousand times and look at the numbers. I suspect you'll find a negligible difference. Micro-optimization is usually a waste of time.

like image 77
Asaph Avatar answered Sep 27 '22 21:09

Asaph


I would imagine not. Are you having performance issues with your script? If not, then don't worry about it. If so, then what have you done to determine where the bottleneck lies?

If you need to know how long it's taking to include and parse the file with your defines in, then I'd suggest you time it.

$start = microtime (true);
include ('file_to_include.php');
echo (microtime (true) - $start);
like image 44
GordonM Avatar answered Sep 27 '22 22:09

GordonM