Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance about replace() or substr() in Javascript

I was wondering about Javascript performance about using string.replace() or string.substr(). Let me explain what I'm doing.

I've a string like

str = "a.aa.a.aa."

I just have to "pop" last element in str where I always know what type of character it is (e.g, it's a dot here).

It's so simple, I can follow a lot of ways, like

str = str.substr(0, str.length-1) // same as using slice()

or

str = str.replace(/\.$/, '')

Which methods would you use? Why? Is there some lack in performance using this or that method? Length of the string is negligible.

(this is my first post, so if I'm doing something wrong please, notify me!)

like image 958
Finalfire Avatar asked Dec 01 '22 23:12

Finalfire


2 Answers

For performance tests in JavaScript use jsPerf.com

I created a testcase for your question here, which shows, that substr is a lot faster (at least in firefox).

like image 106
Sirko Avatar answered Dec 10 '22 11:12

Sirko


If you just want the last character in the string, then use the subscript, not some replacement:

str[str.length-1]
like image 36
Phil H Avatar answered Dec 10 '22 12:12

Phil H