2

I'm developping a web app that deals with large strings and so I want to know which way to get a single char is faster, this one:

var myStr = 'foo';
return myStr[i];

Or this one:

var myStr = 'foo';
return myStr.charAt(i);
Charles
  • 50,943
  • 13
  • 104
  • 142
Danilo Valente
  • 11,270
  • 8
  • 53
  • 67
  • 1
    By the way, [here's a jsperf](http://jsperf.com/charat-vs-arraycall/2) if you wanted to know difference in performance. I think it depends on the browser. – Beat Richartz Jul 19 '12 at 05:37

2 Answers2

4

Accessing characters in a string by index via bracket notation (myStr[i]) not only doesn't work in IE, but is not specified in the ES3 standard (the one all browsers implement correctly).

However, the ES5 specification (the current standard) does include indexed characters (which are supported by modern browsers):

The array index named properties correspond to the individual characters of the String value.

Thus, to write backwards-compatible cross-browser code, you should access individual characters via charAt.

katspaugh
  • 17,449
  • 11
  • 66
  • 103
  • 1
    It will be a valid standard, in the future. Of course, that means that until 2020, for sake of backwards-compatibility with non opt-in JS, you'll be using .charAt, anyway. – Norguard Jul 19 '12 at 05:33
  • @Norguard, that would be cool! Could you link to the proposal/draft? – katspaugh Jul 19 '12 at 05:34
  • 1
    I'd love to go diving through all of ECMAScript5, Harmony and Next to find the official proclamations, but I really don't have the time -- I believe it's a standard within the strict-mode of ES5. Here's an excerpt from the abridged versions of one of the holy grails: http://my.safaribooksonline.com/book/-/9781449335977/6dot-arrays/id3191775 Otherwise, you can hear a few big names (like Crockford, and Moz people) talk about it, in talks -- of course, those talks would be from 2009-2010, probably, talking about the future, which still isn't here. – Norguard Jul 19 '12 at 07:05
  • @Norguard, thanks! It's actually in ES5: http://ecma-international.org/ecma-262/5.1/#sec-15.5.5! – katspaugh Jul 19 '12 at 07:25
3

I'm not sure which is faster, but you might want to look at string.charAt(x) or string[x]? to see discussion on why myStr.charAt(i) is better than using myStr[i] (the answer is browser compatibility)

Community
  • 1
  • 1
megsa
  • 111
  • 1
  • 5
  • Well, this link is util, but as I showed in my edit, I'm acessing the var that contains the string, not it directly – Danilo Valente Jul 19 '12 at 05:26
  • 1
    Also, re:speed, this doesn't show IE, but it shows relative perfomance speeds; running the tests it appears that bracket notation is faster: http://jsperf.com/string-charat-vs-bracket-notation – megsa Jul 19 '12 at 05:32