gpt4 book ai didi

php - 为什么空的 __set() 方法比有效的方法慢?

转载 作者:可可西里 更新时间:2023-11-01 01:01:46 25 4
gpt4 key购买 nike

我在玩弄 PHP 魔法方法(特别是 Property overloading ),并且在进行微基准测试时,遇到了一个我无法解释的怪癖:

看起来一个空体的__set方法比一个有效的方法需要更多的时间来运行。下面的代码片段演示了这一点:

class EmptySetter {
public function __set($name, $value) {}
}

class NonEmptySetter {
public function __set($name, $value) {
$this->{$name} = $value;
}
}

function benchmark($obj) {
$start_time = microtime(TRUE);
for ($i = 0; $i < 10000000; $i++) {
$obj->foo = 42;
}
return microtime(TRUE) - $start_time;
}

printf("EmptySetter: %.2f seconds\n", benchmark(new EmptySetter));
printf("NonEmptySetter: %.2f seconds\n", benchmark(new NonEmptySetter));

// output (on my Core 2 Duo laptop):
// EmptySetter: 4.39 seconds
// NonEmptySetter: 1.28 seconds

有人能解释为什么会这样吗?

最佳答案

哦,我看到这是错误的测试用例。

在第一次循环后 NonEmptySetter 将具有新的公共(public)属性 foo。接下来的循环根本不调用 __set 方法,它们使用公共(public)属性。

class NonEmptySetter {
public function __set($name, $value) {
echo 'called only once'; // would be echoed only once.
$this->{$name} = $value;
}
}

有效测试

class EmptySetter {
public function __set($name, $value) {}
}

class NonEmptySetter {
public function __set($name, $value) {
$this->{$name} = $value;
}
}

function benchmark($class_name) {
$start_time = microtime(TRUE);
for ($i = 0; $i < 1000000; $i++) {
$obj = new $class_name();
$obj->foo = 42;
}
return microtime(TRUE) - $start_time;
}

printf("NonEmptySetter: %.2f seconds\n", benchmark('NonEmptySetter'));
printf("EmptySetter: %.2f seconds\n", benchmark('EmptySetter'));

http://3v4l.org/gVtSq

空 setter 更快。

关于php - 为什么空的 __set() 方法比有效的方法慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23050278/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com