What is the overhead for a hint type in PHP?

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

+4
source share
2 answers

No, that doesn't matter. If you need to do something algorithmically intense, such as sound processing or 3D programming, you should use a different programming language.

if you need hard data, make a guide ...

<?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 faster, sometimes without typing:

$ 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
+5
source

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;

1 000 000 :

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 

, stdClass array, 1 000 000 :

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 
+1

Source: https://habr.com/ru/post/1538620/


All Articles