开发者

PHP array vs PHP Constant?

I am curious, is there any performance gain, like using less memory or resources in PHP for:

50 different setting variables saved into array 开发者_如何学编程like this

$config['facebook_api_secret'] = 'value here';

Or 50 different setting variables saved into a Constant like this

define('facebook_api_secret', 'value here');


I think this is in the realm of being a micro-optimization. That is, the difference is small enough that it isn't worth using one solution over the other for the sake of performance. If performance were that critical to your app, you wouldn't be using PHP! :-)

Use whatever is more convenient or that makes more sense. I put config data into constants if only because they shouldn't be allowed to change after the config file is loaded, and that's what constants are for.


In my informal tests, I've actually found that accessing/defining constants is a bit slower than normal variables/arrays.

it's not going to make a different anyway; more than likely whatever you do with these will happen in thousandths of a second.

Optimizing your DB (indexing, using EXPLAIN to check your queries) and server set up (using APC) will make more a difference in the long run.


Performance gains for 50 variables using a different coding technique / clever programming tricks is the wrong way to do things in PHP. Always remember: the optimizer is smarter than you are.


You will not receive any kind of performance gain for either of these. The real question is which one is more useful.

For scalar values (Strings, ints, etc) that are defined once, should never change, and need to be accessible all over the place, you should use a constant.

If you have some kind of complex nested configuration, eg:

$config->facebook->apikey = 'secret_key';
$config->facebook->url = 'http://www.facebook.com';

You may want to use an array or a configuration api provided by one of the many frameworks out there (Zend_Config isn't bad)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜