10

私はこのページを読んでいました - http://deaduseful.com/blog/posts/50-php-optimisation-tips-revisited

推奨事項の 1 つは、Zend Performance PDF から引用された Magic Methods の使用を避けることでした。

Googleで検索した後(そしてここで無関係な質問にたどり着きました)、誰かがその面で推奨事項を持っているかどうか疑問に思いましたか?

私は自分のコードで __get() をよく使用します。通常は、常に使用するとは限らない変数を保存するためです。

name、dess、category_id、time_added のテーブルがあるかもしれません

私のgetは次のようになります。

public function __get($name) {
    スイッチ($name) {
        ケース「名前」:
        ケース「説明」:
        ケース「カテゴリ」:
        ケース「time_added」:
            $result = do_mysql_query();
            $this->name = $result['name'];
            $this->desc = $result['desc'];
            $this->category = $result['category'];
            $this->time_added = $result['time_added'];
            $this->{$name} を返します。
        壊す;
        デフォルト:
            throw Exception("存在しないプロパティまたはプライベート プロパティにアクセスしようとしました - ".$name);
    }
}

必要な場合にのみデータベースから何かを取得し、配列をいじるのではなく $article->time_added のようなものを参照できるため、これは物事を行うための優れた方法のようです。

これは悪い習慣と見なされ、サーバーに余分な負荷がかかりますか?

多くの場合、魔法のメソッドでクラスを拡張し、子クラスが get の何かと一致しない場合にこのようなことを行います。

public function __get($name) {
    スイッチ($name) {
        ケース「名前」:
        ケース「説明」:
        ケース「カテゴリ」:
        ケース「time_added」:
            $result = do_mysql_query();
            $this->name = $result['name'];
            $this->desc = $result['desc'];
            $this->category = $result['category'];
            $this->time_added = $result['time_added'];
            $this->{$name} を返します。
        壊す;
        デフォルト:
            親を返す::__get($name);
    }
}

これは悪い習慣であり、パフォーマンスに悪いのでしょうか? 魔法のメソッドを拡張するときのレベルの最大数は 3 です。

4

3 に答える 3

17

確かに、それらは遅いです...しかし、違いは非常に小さいため、速度とコードが要因になります。迅速な開発と保守のために、違いについて心配する価値はありますか?

統計の魔法のベンチマークを参照してください

于 2010-09-03T10:16:20.267 に答える
1

配列アクセサーの使用を検討してください。

class Record implements ArrayAccess {

    /**
     * @see ArrayAccess::offsetExists()
     *
     * @param offset $offset
     */
    public function offsetExists($offset) {

    }

    /**
     * @see ArrayAccess::offsetGet()
     *
     * @param offset $offset
     */
    public function offsetGet($offset) {
        //fetch and cache $result

        return $result[$offset];
    }

    /**
     * @see ArrayAccess::offsetSet()
     *
     * @param offset $offset
     * @param value $value
     */
    public function offsetSet($offset, $value) {

    }

    /**
     * @see ArrayAccess::offsetUnset()
     *
     * @param offset $offset
     */
    public function offsetUnset($offset) {

    }
于 2010-09-03T10:24:31.613 に答える