How efficient is define in PHP?

前端 未结 10 1350
不思量自难忘°
不思量自难忘° 2020-12-15 18:38

C++ preprocessor #define is totally different.

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

define(\"SETTING         


        
相关标签:
10条回答
  • 2020-12-15 19:10

    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...
    0 讨论(0)
  • 2020-12-15 19:12
    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.

    0 讨论(0)
  • 2020-12-15 19:14

    Main differences:

    • define is constant, variable is variable
    • they different scope/visibility
    0 讨论(0)
  • 2020-12-15 19:15

    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)
    
    0 讨论(0)
提交回复
热议问题