PHP 中的定义效率如何?

发布于 2024-07-06 12:16:51 字数 243 浏览 3 评论 0原文

C++ 预处理器#define 完全不同。

PHP define() 与仅创建 var 有什么不同吗?

define("SETTING", 0);  
$something = SETTING;

$setting = 0;  
$something = $setting;

C++ preprocessor #define is totally different.

Is the PHP define() any different than just creating a var?

define("SETTING", 0);  
$something = SETTING;

vs

$setting = 0;  
$something = $setting;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

心头的小情儿 2024-07-13 12:16:52

一般来说,常量的概念是在您的程序中保持常量(听起来很有趣,对吧?;))。 这意味着编译器(解释器)将在整个脚本中将“FOOBAR”替换为 FOOBAR 的值。

理论和优点就这么多——如果你编译的话。 现在 PHP 非常动态,在大多数情况下您不会注意到不同,因为 PHP 脚本在每次运行时都会编译。 我可以告诉您,除非您使用字节码缓存,例如 ,否则您不应该看到常量和变量之间的速度存在显着差异APCZend 优化器eAccelerator。 那么它就有意义了。

常量的所有其他优点/缺点已在此处注明,并且可以在 PHP 手册中找到。

In general, the idea of a constant is to be constant, (Sounds funny, right? ;)) inside your program. Which means that the compiler (interpreter) will replace "FOOBAR" with FOOBAR's value throughout your entire script.

So much for the theory and the advantages - if you compile. Now PHP is pretty dynamic and in most cases you will not notice a different because the PHP script is compiled with each run. Afai-can-tell you should not see a notable difference in speed between constants and variables unless you use a byte-code cache such as APC, Zend Optimizer or eAccelerator. Then it can make sense.

All other advantages/disadvantages of constants have been already noted here and can be found in the PHP manual.

素染倾城色 2024-07-13 12:16:52
php > $cat='';$f=microtime(1);$s='cowcow45';$i=9000;while ($i--){$cat.='plip'.$s.'cow';}echo microtime(1)-$f."\n";

0.00689506530762

php > $cat='';$f=microtime(1);define('s','cowcow45');$i=9000;while ($i--){$cat.='plip'.s.'cow';}echo microtime(1)-$f."\n";

0.00941896438599

这是可重复的,结果相似。 在我看来,常量的定义和/或使用比变量要慢一些。

php > $cat='';$f=microtime(1);$s='cowcow45';$i=9000;while ($i--){$cat.='plip'.$s.'cow';}echo microtime(1)-$f."\n";

0.00689506530762

php > $cat='';$f=microtime(1);define('s','cowcow45');$i=9000;while ($i--){$cat.='plip'.s.'cow';}echo microtime(1)-$f."\n";

0.00941896438599

This is repeatable with similar results. It looks to me like constants are a bit slower to define and/or use than variables.

冷弦 2024-07-13 12:16:52

以下是差异,来自 手册

  • 常量没有美元在他们前面签名($);
  • 常量只能使用define()函数来定义,不能通过简单的赋值来定义;
  • 常量可以在任何地方定义和访问,而不考虑变量作用域规则;
  • 常量一旦被设置就不能被重新定义或取消定义; 和
  • 常量只能计算为标量值。

对我来说,主要的好处是全球范围。 我当然不担心它们的效率——只要你需要一个不应该改变的全局标量值,就可以使用它们。

Here are the differences, from the manual

  • Constants do not have a dollar sign ($) before them;
  • Constants may only be defined using the define() function, not by simple assignment;
  • Constants may be defined and accessed anywhere without regard to variable scoping rules;
  • Constants may not be redefined or undefined once they have been set; and
  • Constants may only evaluate to scalar values.

For me, the main benefit is the global scope. I certainly don't worry about their efficiency - use them whenever you need a global scalar value which should not be alterable.

梦在深巷 2024-07-13 12:16:52

看起来效率不高。 (我的所有假设都是基于 php.net 的一条评论,我自己还没有进行基准测试。)

调用一个常量,将花费调用变量时间的 2 倍。

检查常量是否存在需要 2 毫秒,误报则需要 12 毫秒!

这是来自 php 在线文档中定义页面注释的基准。

在使用 Defined() 之前,请查看以下基准:

true                                       0.65ms
$true                                      0.69ms (1)
$config['true']                            0.87ms
TRUE_CONST                                 1.28ms (2)
true                                       0.65ms
defined('TRUE_CONST')                      2.06ms (3)
defined('UNDEF_CONST')                    12.34ms (4)
isset($config['def_key'])                  0.91ms (5)
isset($config['undef_key'])                0.79ms
isset($empty_hash[$good_key])              0.78ms
isset($small_hash[$good_key])              0.86ms
isset($big_hash[$good_key])                0.89ms
isset($small_hash[$bad_key])               0.78ms
isset($big_hash[$bad_key])                 0.80ms

PHP 版本 5.2.6、Apache 2.0、Windows XP

每个语句执行 1000 次,同时开销为 12 毫秒
1000 个电话不会让最终用户抓狂,
与 if(true) 相比,它确实会产生一些有趣的结果:

1) if($true) 几乎相同 2) if(TRUE_CONST) 几乎相同
慢两倍 - 我猜替换不是在编译时完成的
时间(我必须仔细检查这个!)3)define() 慢 3 倍
如果常量存在 4) Defined() 慢 19 倍,如果
常数不存在! 5) isset() 非常高效,无论如何
你扔给它的东西(对于任何实现数组的人来说都是好消息
驱动事件系统 - 我!)

可能想避免 if(define('DEBUG'))...

来自 tris+php at tfconsulting dot com dot au 26-Mar-2009 06:40

http://us.php.net/manual/en/function.define.php#89886

NOT efficient it appears. (And i'm basing all the assumptions here on one comment from php.net, i still haven't did the benchmarks myself.)

recalling a constant, will take 2x the time of recalling a variable.

checking the existence of a Constant will take 2ms and 12ms for a false positive!

Here's a benchmark from the comments of the define page in php's online doc.

Before using defined() have a look at the following benchmarks:

true                                       0.65ms
$true                                      0.69ms (1)
$config['true']                            0.87ms
TRUE_CONST                                 1.28ms (2)
true                                       0.65ms
defined('TRUE_CONST')                      2.06ms (3)
defined('UNDEF_CONST')                    12.34ms (4)
isset($config['def_key'])                  0.91ms (5)
isset($config['undef_key'])                0.79ms
isset($empty_hash[$good_key])              0.78ms
isset($small_hash[$good_key])              0.86ms
isset($big_hash[$good_key])                0.89ms
isset($small_hash[$bad_key])               0.78ms
isset($big_hash[$bad_key])                 0.80ms

PHP Version 5.2.6, Apache 2.0, Windows XP

Each statement was executed 1000 times and while a 12ms overhead on
1000 calls isn't going to have the end users tearing their hair out,
it does throw up some interesting results when comparing to if(true):

1) if($true) was virtually identical 2) if(TRUE_CONST) was almost
twice as slow - I guess that the substitution isn't done at compile
time (I had to double check this one!) 3) defined() is 3 times slower
if the constant exists 4) defined() is 19 TIMES SLOWER if the
constant doesn't exist! 5) isset() is remarkably efficient regardless
of what you throw at it (great news for anyone implementing array
driven event systems - me!)

May want to avoid if(defined('DEBUG'))...

from tris+php at tfconsulting dot com dot au 26-Mar-2009 06:40

http://us.php.net/manual/en/function.defined.php#89886

愿与i 2024-07-13 12:16:52

Define是简单的静态意义,意味着它的值在运行时不能改变,而变量是动态意义,因为你可以在过程中自由地操纵它的值。

Define is simple static sense, meaning its value can't be changed during runtime while variable is dynamic sense because you can freely manipulate its value along the process.

淡淡離愁欲言轉身 2024-07-13 12:16:52

当我运行速度测试时,设置和转储常量的运行速度比设置变量并转储它们的速度要快得多。

When I run speed tests, constants being set and dumped out run much a little faster than setting variables and dumping them out.

︶葆Ⅱㄣ 2024-07-13 12:16:52

2020 更新(PHP 7.2、AMD Ryzen9、启用 Zend OpCache)

总结:重新定义相同的常量很慢。 检查和定义
常量 vs $_GLOBALS 大约慢 8 倍,检查未定义
常数稍微慢一些。 不要使用全局变量。

  • 注意:自动加载器和需要一次长路径可能会产生比定义大得多的问题。 (需要一次需要 php stat(2) 路径中的每个目录来检查符号链接,这可以通过使用文件的完整路径来减少,这样 PHP 加载器只需统计文件路径 1x 并可以使用统计缓存)

代码:

$loops = 90000;
$m0 = microtime(true);
for ($i=0; $i<$loops; $i++) {
   define("FOO$i", true);
}
$m1 = microtime(true);
echo "Define new const {$loops}s: (" . ($m1-$m0) . ")\n";
// etc...

输出:

Define new const 90000s: (0.012847185134888)
Define same const 90000s: (0.89289903640747)
Define same super global 90000s: (0.0010528564453125)
Define new super global 90000s: (0.0080759525299072)
check same undefined 90000s: (0.0021710395812988)
check same defined 90000s: (0.00087404251098633)
check different defined 90000s: (0.0076708793640137)

2020 update (PHP 7.2, AMD Ryzen9, Zend OpCache enabled)

summary: redefining the same constant is slow. checking and defining
constants vs $_GLOBALS is about 8x slower, checking undefined
constants is slightly slower. Don't use globals.

  • note: auto loaders and require once long paths are likely to be much larger problems than defines. (require once requires php to stat(2) every directory in the path to check for sym links, this can be reduced by using full paths to your file so the PHP loader only has to stat the file path 1x and can use the stat cache)

CODE:

$loops = 90000;
$m0 = microtime(true);
for ($i=0; $i<$loops; $i++) {
   define("FOO$i", true);
}
$m1 = microtime(true);
echo "Define new const {$loops}s: (" . ($m1-$m0) . ")\n";
// etc...

OUTPUT:

Define new const 90000s: (0.012847185134888)
Define same const 90000s: (0.89289903640747)
Define same super global 90000s: (0.0010528564453125)
Define new super global 90000s: (0.0080759525299072)
check same undefined 90000s: (0.0021710395812988)
check same defined 90000s: (0.00087404251098633)
check different defined 90000s: (0.0076708793640137)
别低头,皇冠会掉 2024-07-13 12:16:52

主要区别:

  • 定义是常量,变量是变量,
  • 它们的范围/可见性不同

Main differences:

  • define is constant, variable is variable
  • they different scope/visibility
三五鸿雁 2024-07-13 12:16:52

不确定效率,但它不仅仅是创建一个 var:

  • 它是一个常量:您不能重新定义或重新分配此设置。
  • 如果未找到定义,$something 将设置为“SETTING”,这很有用,例如,在 i18n 中:如果缺少翻译(即相应的定义是本地化文件),我们会在大写,很明显...

Not sure about efficiency, but it is more than creating a var:

  • It is a constant: you can't redefine or reassign this SETTING.
  • If the define isn't found, $something is set to "SETTING", which is useful, for example, in i18n: if a translation is missing (ie. the corresponding define is the localization file), we see a big word in uppercase, quite visible...
简单爱 2024-07-13 12:16:51

“定义”操作本身相当慢 - 由 xdebug 分析器确认。

这是来自 http://t3.dotgnu.info/blog 的基准/php/my-first-php-extension.html:

  • 纯“定义”
    380.785 次读取/秒
    14.2647 平均毫秒/第一响应

  • 用“hidef”扩展定义的常数
    930.783 次读取/秒
    6.30279 平均毫秒/第一响应


损坏的链接更新

上面引用的博客文章已离开互联网。 仍然可以查看 此处通过 Wayback Machine。 这是另一篇类似文章

作者引用的库可以在此处 (apc_define_constants)此处(hidef 扩展)

'define' operation itself is rather slow - confirmed by xdebug profiler.

Here is benchmarks from http://t3.dotgnu.info/blog/php/my-first-php-extension.html:

  • pure 'define'
    380.785 fetches/sec
    14.2647 mean msecs/first-response

  • constants defined with 'hidef' extension
    930.783 fetches/sec
    6.30279 mean msecs/first-response


broken link update

The blog post referenced above has left the internet. It can still be viewed here via Wayback Machine. Here is another similar article.

The libraries the author references can be found here (apc_define_constants) and here (hidef extension).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文