1

In another question I came across two different ways of doing a string replacement.

One being the jQuery way $("#element").text().replace(',', '.') and the other being the pure Javascript way of first getting the text and then calling .replace(/,/, '.').

Is there a big performance hit in using the jQuery method, or any other reason not to use it (assuming you already have jQuery on the page)?

Community
  • 1
  • 1
Ola Karlsson
  • 9,011
  • 7
  • 27
  • 37

4 Answers4

3

These are both essentially the same method.

$('#element').text() returns a string, so you're calling String.prototype.replace() in both examples.

The only difference I can see is that in the first method, you are using a string for the replacement, and in the 2nd, you are using a regular expression. In the examples you gave, the string method will be faster:

http://jsperf.com/string-replace-vs-regexp

If you really want to get the best performance, I'd suggest using pure JavaScript:

document.getElementById( 'element' ).innerText.replace( ',', '.' )

Robert Messerle
  • 3,022
  • 14
  • 18
0

Both methods of replacing are exactly the same, admittedly one is using a string, the other a regex but the underlying javascript replace method is the same. The only difference is the method in which the string to perform the replace on is retreieved.

The jQuery method of retreieval will be marginally slower, but not in any noticeable way.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0

Generally speaking, jQuery is almost always going to be slower, though the advantages usually outweigh the hit in performance. In this case, I suspect jQuery simply added this method to offer a more convenient means to do the same thing.

Unless you're going lots of replace calls, I wouldn't even worry about it.

Neil
  • 5,762
  • 24
  • 36
0

You are virtually doing the same thing. But if speed is meant to be considered. Be more precise on your jQuery selector.

Joberror
  • 5,860
  • 3
  • 20
  • 15