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);
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);
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
.
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)