PHP中类型提示的性能开销是多少?

Ala*_*air 6 php performance type-hinting

PHP中类型提示的性能开销有多大 - 它是否足以成为决定使用它的一个考虑因素?

Mic*_*ael 5

不,这不重要.如果你需要做一些算法密集的事情,比如声音处理或3D编程,你应该使用另一种编程语言.

如果你想要硬数据,做一个基准......

<?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"));
Run Code Online (Sandbox Code Playgroud)

在我的电脑上,性能是一样的.有时它更快,有时没有打字:

$ 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
Run Code Online (Sandbox Code Playgroud)