更好地使用setter和getter

时间:2012-07-06 07:06:40

标签: actionscript-3 oop setter getter

我对魔法方法getter和setter有疑问。

我的问题是:什么更好(更快,更安全)?

P.S。这是ActionScript 3,但问题可以回答其他语言,如PHP,JavaScript,C#等。

案例1

    public class Test extends Sprite
    {
        private var _test : uint = 0;

        public function Test()
        {
            start();
        }

        private function start() : void
        {
            trace(_test); ** Take the private var _test **
        }

        public function set test(value : uint) : void
        {
            _test = value;
            start();
        }

        public function get test() : uint
        {
            return _test;
        }
   }

或案例2

    public class Test extends Sprite
    {
        private var _test : uint = 0;

        public function Test()
        {
            start();
        }

        private function start() : void
        {
            trace(test); ** difference here, take the public function test **
        }

        public function set test(value : uint) : void
        {
            _test = value;
            start();
        }

        public function get test() : uint
        {
            return _test;
        }
   }

什么是最好(最快)的方式?

谢谢!

2 个答案:

答案 0 :(得分:5)

你大约有90%的时间来编写自己的测试用例来发现自己......

Getters和setter旨在添加对设置或检索属性时发生的事情的控制,或者创建只读或只写属性。

这些好处远远超过任何可能的性能差异。


至于那些性能差异,这是一个测试环境:

// Test property.
var _test:uint = 0;
function get test():uint{ return _test; }
function set test(value:uint):void{ _test = value; }

// Direct access test.
function directTest(amt:int):Number
{
    // Directly accessing the property.
    var t:Number = getTimer();
    for(var i:int = 0; i < amt; i++)
    {
        var temp:uint = _test;
        _test = i;
    }

    return getTimer() - t;
}


// Getter/setter test.
function viaTest(amt:int):Number
{
    // Via getter/setter.
    var t:Number = getTimer();
    for(var i:int = 0; i < amt; i++)
    {
        var temp:uint = test;
        test = i;
    }

    return getTimer() - t;
}

快速演示如何使用它:

trace("Direct: " + directTest(1000000));
trace("Getter/Setter: " + viaTest(1000000));

我得到了一些结果:

Amount      Direct      Get/Set
1000        0           0
5000        0           0
20,000      0           2
150,000     1           14
500,000     2           46
2,000,000   10          184
10,000,000  47          921

答案 1 :(得分:2)

我总是喜欢将getter和setter也用于声明它们的同一个类的方法中(虽然我可以使用privare变量)。

getter和setter隐藏了必须设置或获取类属性时所需的逻辑,因此您可以在setter / getter中修改“您实际操作的内容”,而无需担心客户端方法的影响。

他们也避免重复代码。

但这只是我的观点......:)