Performance about replace() or substr() in Javascript

Finalfire picture Finalfire · Mar 6, 2012 · Viewed 11.5k times · Source

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!)

Answer

Sirko picture Sirko · Mar 6, 2012

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