3

私は 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

なぜこれが起こっているのかについて誰かが説明していますか?

4

2 に答える 2

2

ああ、間違ったテストケースだと思います。

最初のループの後NonEmptySetter、新しいパブリック プロパティが追加されますfoo。次のループはメソッドをまったく呼び出さず__set、パブリック プロパティを使用します。

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

空のセッターの方が高速です。

于 2014-04-14T02:05:44.957 に答える