Via. or [] to access the properties of an object - what's the difference?

What is the difference between code (i) and (ii) below?

(I)

var obj:Object = new Object(); obj.attribute = value ; 

(Ii)

 var obj:Object = new Object(); obj["key"] = value; 

Are there any consequences at runtime if I write this:

 var obj:Object = new Object(); obj.somekey = value1 ; obj["someKey"] = value2 ; 

Explain, please.

+6
source share
1 answer

The difference lies in the search mechanism: if you use point syntax, the compiler will know at compile time that you are accessing a property of this object. If you use parenthesis syntax, the actual property search is performed at run time, and there will be more type checking. In the end, you could compose a key string dynamically, the value could change, or you could even call a function instead of a variable, etc.

The result is a significant performance difference: The parenthesis syntax takes about three times as much as the point syntax.

Here's a quick speed test to illustrate my point:

 var start : int = getTimer(); var obj:Object = { something : "something" }; for (var i : int = 0; i < 100000000; i++) { var n:String = obj.something; } trace ("Time with dot syntax: "+(getTimer() - start)); start = getTimer(); for (i = 0; i < 100000000; i++) { var o:String = obj["something"]; } trace ("Time with bracket syntax: "+(getTimer() - start)); 

If they were the same, except for the designations, they should have taken exactly the same amount of time. But, as you can see, this is not so. On my car:

 Time with dot syntax: 3937 Time with bracket syntax: 9857 
+21
source

Source: https://habr.com/ru/post/907398/


All Articles