5

What is the more efficient way to write this:

if ($('.shipping .price').text() === "FREE"){ 
    $('.shipping .price').addClass('text-primary'); 
}

OR

$('.shipping .price:contains("FREE")').addClass('text-primary');
Aquazie
  • 69
  • 3
  • 8
    Well the two are not equivalent, to start with. The second can match more nodes than the first one. – dfsq May 14 '16 at 21:34
  • Even the question itself is ambiguous ... second is obviously less lines of code and more *"efficient to write"* but that doesn't necessarily equate to *"more efficient to process"* – charlietfl May 14 '16 at 21:53
  • 1
    Assuming this is about performance, your situation might be splitting hairs but this might be a good read: http://stackoverflow.com/questions/111368/how-do-you-performance-test-javascript-code – Stu Furlong May 14 '16 at 22:03
  • The first one only tests the contents of the first element that matches the selector, but then it adds the class to **all** of them. The second version tests the contents of each element that matches the classes, and adds the new class to each one that contains `FREE`. – Barmar May 14 '16 at 22:47

1 Answers1

3

A quick test shows that the code with if runs about 5 times faster than the one with the contains-selector. However, as others already explained in the comments, the two are not equivalent.

You could speed things up even more by caching the call to $('.shipping .price') like this:

var elem = $('.shipping .price');
if (elem.text() === "FREE"){ 
  elem.addClass('text-primary'); 
}

However, for almost every real-life scenario performance differences will not matter at all and you should go for the option that is more efficient to read for other humans. If you really care for performance (for example if you have a rather large price list) you should use vanilla JS wich is about another 10 times faster in this case.

amoebe
  • 4,857
  • 5
  • 37
  • 42