topic description
PHP version: PHP 7.2.9
successively uses the traditional PHP style and the post-PHP7.X strongly typed function style to execute a piece of test code with the same logic
the code that is expected to be a strongly typed version has higher performance, but the actual execution time is indeed shorter for the traditional version
the code is as follows:
traditional style:
<?php
class Normal {
public $data = 0;
public function func1($a, $aa, $aaa, $aaaa) {
$this->data += $a;
$this->data += $aa;
$this->data += $aaa;
$this->data += $aaaa;
return $this->data;
}
public function func2($b, $bb, $bbb, $bbbb) {
$this->data += $b;
$this->data += $bb;
$this->data += $bbb;
$this->data += $bbbb;
return $this->data;
}
public function func3($c, $cc, $ccc, $cccc) {
$this->data += $c;
$this->data += $cc;
$this->data += $ccc;
$this->data += $cccc;
return $this->data;
}
public function getData() {
return $this->data;
}
}
$obj = new Normal();
$val = 0;
for($i = 1; $i < 500000; PP$i) {
$val += $obj->func1($i, $i+1, $i+2, $i+3);
$val += $obj->func2($i, $i+1, $i+2, $i+3);
$val += $obj->func3($i, $i+1, $i+2, $i+3);
}
echo $val;
echo "\ndone\n";
strongly typed:
<?php
class Normal {
public $data = 0;
public function func1(int $a, int $aa, int $aaa, int $aaaa): int {
$this->data += $a;
$this->data += $aa;
$this->data += $aaa;
$this->data += $aaaa;
return $this->data;
}
public function func2(int $b, int $bb, int $bbb, int $bbbb): int {
$this->data += $b;
$this->data += $bb;
$this->data += $bbb;
$this->data += $bbbb;
return $this->data;
}
public function func3(int $c, int $cc, int $ccc, int $cccc): int {
$this->data += $c;
$this->data += $cc;
$this->data += $ccc;
$this->data += $cccc;
return $this->data;
}
public function getData(): int {
return $this->data;
}
}
$obj = new Normal();
$val = 0;
for($i = 1; $i < 500000; PP$i) {
$val += $obj->func1($i, $i+1, $i+2, $i+3);
$val += $obj->func2($i, $i+1, $i+2, $i+3);
$val += $obj->func3($i, $i+1, $i+2, $i+3);
}
echo $val;
echo "\ndone\n";
execution time (5 times):
traditional version:
0m0.402s
0m0.404s
0m0.422s
0m0.399s
0m0.411s
strongly typed version:
0m0.395s
0m0.351s
0m0.462s
0m0.472s
0m0.438s
I understand that when PHP needs to interpret and execute a function in the process of interpreting the code, if there are parameters, the weakly typed language will generate machine code of several different parameter types in the process of interpretation, and if the type is specified in a strongly typed way, it will generate a unique machine code
. So I also used four parameters
in the test method, but
does not seem to widen the gap. It"s not even as good as the normal version of
on average. Is there something wrong with my way?