Is the Javascript String length constant time?

后端 未结 6 2168
萌比男神i
萌比男神i 2020-12-18 20:15

I\'m fairly new to JS, and realize length is considered a property. But I received a comment to not use str.length in a loop:

for (i=0; i

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-18 21:06

    W3Schools recommends that you use this:

    l = arr.length;
    for (i = 0; i < l; i++) {..}
    

    instead of this:

    for (i = 0; i < arr.length; i++) {...}
    

    Claiming that:

    The bad code accesses the length property of an array each time the loop is iterated.

    The better code accesses the length property outside the loop, and makes the loop run faster.


    Is it better to store frequently accessed values in a local variable?

    Because w3schools is evil, let me quote from another source (Writing Efficient JavaScript - Nicholas C. Zakas).

    ... The important lesson to take from this information is to always store frequently accessed values in a local variable. Consider the following code:

    function process(data){
        if (data.count > 0){
            for (var i=0; i < data.count; i++){
                processData(data.item[i]);
            }
        }
    }
    

    ...The function will run faster if this value is stored in a local variable and then accessed from there:

    function process(data){
        var count = data.count;
        if (count > 0){
            for (var i=0; i < count; i++){
    
                processData(data.item[i]);
            }
        }
    }
    

    Why property accessing is slower than accessing instance variables?

    From here:

    Most JavaScript engines use a dictionary-like data structure as storage for object properties - each property access requires a dynamic lookup to resolve the property's location in memory. This approach makes accessing properties in JavaScript typically much slower than accessing instance variables in programming languages like Java and Smalltalk.


    Why performance benchmarking doesn't show any differences?

    In general some (or most) JavaScript engines use optimization techniques to improve the property access time like this one by V8.

    Also, JavaScript string objects might be of a different nature as you cannot add properties dynamically to them. (which makes the dynamic lookup unnecessary.. I guess)


    Conclusion

    For string.length use any of the two code snippets. But for other object types or properties that do computations, then you have to benchmark your code performance first (or just store the value in a local variable).

提交回复
热议问题