PHP 中类型提示的性能开销是多少? [英] What is the performance overhead of type-hinting in PHP?

查看:62
本文介绍了PHP 中类型提示的性能开销是多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP 中类型提示的性能开销有多大 - 在决定是否使用它时是否足够重要?

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?

推荐答案

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

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

这篇关于PHP 中类型提示的性能开销是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆