PHP - Zend say avoid Magic Methods?

好久不见. 提交于 2019-12-03 12:59:54
Ashley

It's true, they are slower... but the difference is so tiny that speed vs code is a factor. Is it worth worrying about the difference for quicker development and maintenance?

See magic benchmarks for stats

Consider using array accessors.

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) {

    }

I did some tests with PHP magic methods and native get/set operations (on a public property)

The results:

Magic methods are much slower than native access. BUT access time is still so small, that it will not make a difference in 99.9% of all cases.

Even if you do 1 Million magic method accesses within one request, it still only takes about 0.1 second...


"Read only" means access via magic methods. The image shows PHP 5.5.9 and PHP 7.0 results.

Here is the benchmark script: https://github.com/stracker-phil/php-benchmark/blob/master/benchmark.php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!