Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between .substr(0,1) or .charAt(0)?

We were wondering in this thread if there was a real difference between the use of .substr(0,1) and the use of .charAt(0) when you want to get the first character (actually, it could apply to any case where you wan only one char).

Is any of each faster than the other?

like image 709
JMax Avatar asked Jul 05 '11 08:07

JMax


People also ask

What's the difference between substring and slice?

Parameter Consistency A big difference with substring() is that if the 1st argument is greater than the 2nd argument, substring() will swap them. slice() returns an empty string if the 1st argument is greater than the 2nd argument.

What is the difference between substring and Substr?

The difference between substring() and substr()The two parameters of substr() are start and length , while for substring() , they are start and end . substr() 's start index will wrap to the end of the string if it is negative, while substring() will clamp it to 0 .

What is the use of charAt () method?

The charAt() method returns the character at the specified index in a string. The index of the first character is 0, the second character is 1, and so on.

How do you check if the first character of a string is a specific character?

Using the isDigit() method Therefore, to determine whether the first character of the given String is a digit. The charAt() method of the String class accepts an integer value representing the index and returns the character at the specified index.


2 Answers

Unless your whole script is based on the need for doing fast string manipulation, I wouldn't worry about the performance aspect at all. I'd use charAt() on the grounds that it's readable and the most specific tool for the job provided by the language. Also, substr() is not strictly standard, and while it's very unlikely any new ECMAScript implementation would omit it, it could happen. The standards-based alternatives to str.charAt(0) are str.substring(0, 1) and str.slice(0, 1), and for ECMAScript 5 implementations, str[0].

like image 28
Tim Down Avatar answered Oct 04 '22 20:10

Tim Down


Measuring it is the key!

Go to http://jsperf.com/substr-or-charat to benchmark it yourself.

substr(0,1) runs at 21,100,301 operations per second on my machine, charAt(0) runs 550,852,974 times per second.

I suspect that charAt accesses the string as an array internally, rather than splitting the string.

As found in the comments, accessing the char directly using string[0] is slightly faster than using charAt(0).

like image 104
Rich Bradshaw Avatar answered Oct 04 '22 22:10

Rich Bradshaw