Javascript property access speed: difference var.property vs. var[“property”]?

后端 未结 3 1179
野的像风
野的像风 2021-01-18 12:35

I have a very basic JavaScript question.

I am writing a program which will generate JavaScript code. for accessing a property of a variable i have two choices:

相关标签:
3条回答
  • 2021-01-18 12:47

    There are no static properties in Javascript, only dynamic property accessing exists.

    Properties are always queried in the same way regardless of what syntax you put in your source code file.

    Use jshint to recommend good source code conventions for your JS files:

    http://jshint.com/

    Dot notation is always recommended. Use quotation mark notation only if your Javascript property has not id which passes in JS syntax.

    0 讨论(0)
  • 2021-01-18 13:02

    Emphazise code reusability and maintainability. When you are done, and IF it runs slow, try to see WHERE it is running slow and better it.

    So, is there any difference between object.property and obj["property"] in terms of eficciency? I don't think so, but mostly I don't think you should bother until you have encountered a performance issue with your finished, working code. This last part should be your worry.

    And even if you find out that your code runs slow, I bet you this will NOT be the reason.

    0 讨论(0)
  • 2021-01-18 13:02

    I did this test on Node.JS

    var obj = {test:"test"}
    
    var time1 = new Date();
    var t1 = time1.getTime();  
    
    for(i = 0; i < 1000000000; i++){
      obj.test;
    }
    
    var time2 = new Date();
    var t2 = time2.getTime();
    
    console.log(t2-t1)
    
    var time3 = new Date();
    var t3 = time3.getTime();
    
    for(i = 0; i < 1000000000; i++){
      obj["test"];
    }
    
    var time4 = new Date();
    var t4 = time4.getTime();
    
    console.log(t4-t3)  
    

    I find both perform almost the same, with obj.test performing a tiny bit better than obj["test"]

    0 讨论(0)
提交回复
热议问题