0

JavaScript n00b here. I have the following block of code in the webpage I'm making:

    for (var k = 0, n = startingText.length; k < n; ++k)
    {
        if (startingText[k] in map1)
            ++map1[startingText[k]];
        else
            map1[startingText[k]] = 1;
    }

However, I presume this can and should be optimized. I don't want to have to call the access operator on startingText when I'm iterating through its elements sequentially. Or does it matter? I learned C++ before I tried learning JavaScript, so my intuition says there must exist some JavaScript equivalent of iterating through the pointers to the characters of startingText and dereferencing them to get their values.

user3461018
  • 139
  • 1
  • 2
  • 9
  • It does according to here: http://stackoverflow.com/questions/6298169/how-to-create-a-map-object-in-a-javascript – user3461018 Mar 25 '14 at 19:50

1 Answers1

3

No, it doesn't matter. Even your for loop has a premature an unnecessary optimization: Just use string.length. Don't cache that value.

for (var i = 0; i < startingText.length; ++i) {
  var ch = startingText[i];

  // ...
}

JavaScript is not C++, and it has completely different performance characteristics. Trying to apply C++/pointer-specific optimizations isn't going to yield noticeable benefits, and it's just going to produce unnecessarily complex code.

I presume this can and should be optimized

Your presumption is wrong; it should be optimized for speed if you find it's actually a performance bottleneck. Otherwise, it should be optimized for maintainability/readability.

user229044
  • 232,980
  • 40
  • 330
  • 338