开发者

Use "is" or "as" in this case?

I have these interfaces:

public interface IBaseInterface
{
    function Method():void:
}

public interface IExtendedInterface extends IBaseInterface
{
    function MethodTwo():void;
}

...and a vector of type "IBaseInterface" I need to iterate through:

var myVector:Vector.<IBaseInterface开发者_JS百科> = new Vector.<IBaseInterface>();

I need to perform an operation on objects that use IExtendedInterface. Which is the preferred option?

for each(var obj:IBaseInterface in myVector)
{
    // Option 1:
    var tmp:IExtendedInterface = obj as IExtendedInterface;

    if(tmp != null)
        tmp.MethodTwo();

    // Option 2:
    if(obj is IExtendedInterface)
        IExtendedInterface(obj).MethodTwo();
}

I'm sure the info I'm looking for is out there, it's just hard to search for "is" and "as"...Thanks in advance!


I tried a little test to find out which is faster, expecting the "as" variant to be slightly better, because a variable assignment and check for null seem less complex than a type comparison (both options include a type cast) - and was proven right.

The difference is minimal, though: At 100000 iterations each, option 1 was consistently about 3 milliseconds(!) faster.


As weltraumpirat says, Option 1 is faster,

But if you are working on your own code, and no one else is going to ever touch it then go for it.

But if its a team collaboration and you are not going to run the operation 100,000 times with mission critical to the millisecond timings, then Option 2 is much easier for someone looking through your code to read.

Especially important if you are giving your code over to a client for further development.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜