What is the performance overhead of type-hinting in PHP?

蹲街弑〆低调 提交于 2021-02-07 06:44:25

问题


How significant is the performance overhead of type-hinting in PHP - is it significant enough to be a consideration in the decision to use it or not?


回答1:


No, it's not significant. If you need to do something algorithmically intensive, like sound-processing or 3D-programming, you should use another programming language.

if you want hard data, make a benchmark...

<?php

function with_typehint(array $bla)
{
    if(count($bla) > 55) {
        die("Array to big");
    }
}

function dont_typehint($bla)
{
    if(count($bla) > 55) {
        die("Array to big");
    }   
}

function benchmark($fn)
{
    $start = microtime(TRUE);
    $array = array("bla", 3);
    for($i=0; $i<1000000; $i++) {
        $fn($array);
    }
    $end = microtime(TRUE);
    return $end-$start;
}

printf("with typehint: %.3fs\n", benchmark("with_typehint"));
printf("dont typehint: %.3fs\n", benchmark("dont_typehint"));

on my computer, the performance is the same. sometimes its faster with, sometimes without typehinting:

$ php Documents/type_hinting.php 
with typehint: 0.432s
dont typehint: 0.428s

$ php Documents/type_hinting.php 
with typehint: 0.414s
dont typehint: 0.416s



回答2:


You can find the answer by creating a simple bechmark, for example:

$test1 = function(stdClass $obj){};
$test2 = function($obj){};

$begin = microtime(true);
for ($i = 0; $i < 1000000; $i++){
    $test1(new stdClass);
}
$end = microtime(true);

$timeElapsedTest1 = $end - $begin;

$begin = microtime(true);
for ($i = 0; $i < 1000000; $i++){
    $test2(new stdClass);
}
$end = microtime(true);

$timeElapsedTest2 = $end - $begin;

echo 'difference: ', $timeElapsedTest1 - $timeElapsedTest2;

Differences for 1 000 000 loops on my computer:

1.  0.0994789600372 ms 
2.  0.0944871902466 ms 
3.  0.103265047073 ms 
4.  0.0899112224579 ms 
5.  0.0860922336578 ms 
6.  0.0973558425903 ms 
7.  0.0905900001526 ms 
8.  0.0891189575195 ms 
9.  0.09983086586 ms 
10. 0.0914621353149 ms 

After I replaced stdClass with array, differences for 1 000 000 loops on my computer changed a bit:

1.  0.00209307670593 ms 
2.  0.00217390060425 ms 
3.  0.00558805465698 ms 
4.  0.00264406204224 ms 
5.  0.00367116928101 ms 
6.  0.00262594223022 ms 
7.  0.00353169441223 ms 
8.  0.00217604637146 ms 
9.  0.00049090385437 ms 
10. 0.002516746521 ms 


来源:https://stackoverflow.com/questions/23371432/what-is-the-performance-overhead-of-type-hinting-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!