1

The two ways I know to set the id of an element in javascript are as follows:

var myDiv = document.createElement('div');
$(myDiv).attr('id', 'myDiv');

var myDiv = document.createElement('div');
myDiv.id = 'myDiv';

I'm guessing the second one is better because it doesn't use jQuery, is this true?

MarksCode
  • 8,074
  • 15
  • 64
  • 133
  • 1
    It's better because it's more readable. – Ry- Jul 19 '16 at 21:36
  • 1
    Yes. The second one is faster for several reasons. – Ram Jul 19 '16 at 21:36
  • If you're going to use jQuery in the first example, you might as well `var myDiv = $('
    ').attr('id', 'myDiv').get(0);`
    – Patrick Roberts Jul 19 '16 at 21:36
  • I think `attr()` us using `myDiv.id` inside its code,so it is slower. But jQuery resolves cross browser issues. use js performance tools to test yourself. there is also `prop()` – Adib Aroui Jul 19 '16 at 21:36
  • @whitelettersinblankpapers "cross browser issues" for setting an `id` attribute/property? – Ram Jul 19 '16 at 21:37
  • @Vohuman, no, cross browser issues when compared to performance whenever we ask `jQuery vs Vanilla javascript` – Adib Aroui Jul 19 '16 at 21:38
  • @whitelettersinblankpapers, `id` is an attribute, not a property. Do not use `.prop()` to set an element's `id`. – Patrick Roberts Jul 19 '16 at 21:40
  • 4
    @PatrickRoberts: Huh? The point is that you *should* use `.prop` to set the `.id` property. (Which in turn reflects in an attribute, but nobody cares about that) – Bergi Jul 19 '16 at 21:42
  • 1
    @PatrickRoberts Check http://stackoverflow.com/questions/6003819/properties-and-attributes-in-html – Ram Jul 19 '16 at 21:43
  • 1
    @Vohuman, thank you for the link, this is advanced notions (to me) I used to use `prop()` instead of `attr()` for id : https://jsfiddle.net/x4o96u6d/1/ – Adib Aroui Jul 19 '16 at 21:50

3 Answers3

2

Yes, the vanilla javascript solution will be the fastest here (although in this case we are talking extreme microseconds).

Function calls are expensive. And when you call .attr, you are making a function call (defined in the jQuery library) which then ends up doing essentially the native method anyways.

As @Vohuman has also pointed out in the comment on this answer, you also have the overhead of even creating the jQuery instance for the elements passed to it. To even begin though with jQuery though, have to include the jQuery library which also takes up time.

KevBot
  • 17,900
  • 5
  • 50
  • 68
  • 1
    Actually `.attr` will create an attribute insted of setting the `.id` property (which is another turn slower) – Bergi Jul 19 '16 at 21:41
  • "*jQuery instances have a lot of properties*" - uh, no. They're actually as lightweight as possible (which of course is still more than no instance at all, but it's not significant) – Bergi Jul 19 '16 at 21:43
  • @Bergi, maybe I'll rephrase that section. I was meaning methods such as all the protoypes, etc – KevBot Jul 19 '16 at 21:45
  • But prototype methods don't take any memory - that's their entire point of being shared. Of course, loading and initialising the jQuery library in the first place does have a significant overhead, but we'll disregard that assuming that it is needed anyway. – Bergi Jul 19 '16 at 21:47
2

You can measure the duration of functions by repeating the execution in a loop. Measure the seconds and calculate the difference. It is about 7.5 times faster. You can execute the measurement right now, right here:

var loops = 100000;

var beforeJQuery = Date.now();

for(var i = 0; i < loops; i++) {
  var myDiv = document.createElement('div');
  $(myDiv).attr('id', 'myDiv');
}

var beforeVanilla = Date.now();

for(var i = 0; i < loops; i++) {
  var myDiv = document.createElement('div');
  myDiv.id = 'myDiv';
}

var afterVanilla = Date.now();

var executionTimeJQuery = (beforeVanilla - beforeJQuery);
var executionTimeVanilla = (afterVanilla - beforeVanilla)

console.log(executionTimeJQuery + "ms took the execution of the jQuery method for " + loops + " loops. This is ~" + (executionTimeJQuery / loops) + "ms  per execution.");
console.log(executionTimeVanilla + "ms took the execution of the vanilla method for " + loops + " loops. This is ~" + (executionTimeVanilla / loops) + "ms  per execution.");

console.log("The vanilla method is " + (executionTimeJQuery / executionTimeVanilla) + " faster than the jQuery method.");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
ssc-hrep3
  • 15,024
  • 7
  • 48
  • 87
1

Approximately 10 times faster.

const iterations = 10000;
const myDiv = document.createElement('div');

console.time('jQuery');
  for (let i = 1; i < iterations; i++) {
    $(myDiv).attr('id', 'myDiv');
  }
console.timeEnd('jQuery');

const myDiv2 = $(myDiv);
console.time('jQuery with object');
  for (let i = 1; i < iterations; i++) {
    myDiv2.attr('id', 'myDiv');
  }
console.timeEnd('jQuery with object');

const myDiv3 = document.createElement('div');

console.time('Vanila Javascript');
  for (let i = 1; i < iterations; i++) {
    myDiv3.id = 'myDiv';
  }
console.timeEnd('Vanila Javascript');

jQuery: 41.998ms
jQuery with object: 32.513ms
Vanila Javascript: 4.670ms

Edit:

If you have jQuery in project you can use it without that speed difference is not significant. This micro optimization is not wort it. If you are not making Javascript FPS game :)

Edit2: @Bergi adding createElement in the timing function will not change the results significantly as you can see below.

const iterations = 10000;

console.time('jQuery');
  const myDiv = document.createElement('div');
  for (let i = 1; i < iterations; i++) {
    $(myDiv).attr('id', 'myDiv');
  }
console.timeEnd('jQuery');


console.time('jQuery with object');
  const myDiv2 = $(document.createElement('div'));
  for (let i = 1; i < iterations; i++) {
    myDiv2.attr('id', 'myDiv');
  }
console.timeEnd('jQuery with object');

console.time('Vanila Javascript');
  const myDiv3 = document.createElement('div');
  for (let i = 1; i < iterations; i++) {
    myDiv3.id = 'myDiv';
  }
console.timeEnd('Vanila Javascript');

jQuery: 35.493ms
jQuery with object: 21.310ms
Vanila Javascript: 4.515ms
Marcel Mandatory
  • 1,447
  • 13
  • 25
  • Wow, that's a big difference. Glad I asked because I'm doing this about 20 times in my code which adds up. – MarksCode Jul 19 '16 at 21:46
  • What value did you use for `iterations` to get so many milliseconds? – Bergi Jul 19 '16 at 21:48
  • I think you should include the `document.createElement('div');` in the timing, it will contribute the significant part. Also setting a property value of an existing element to the value it already has is a no-op that could be completely optimised away. – Bergi Jul 19 '16 at 21:50
  • 2
    @MarksCode: But doing this 20 times is nothing. Even if you are using jQuery, those 20 times will take 0.08ms according to the measurements in this answer. A tenfold of nothing is still nothing. As Ryan O'Hara said in the first comment to your answer, you should choose the more readable and maintainable one, not the faster one (although it often is the same). – Bergi Jul 19 '16 at 21:53