Reputation: 533
Consider this example code:
function appendText()
{
var txt1="<p>Text.</p>"; // Create element with HTML
var txt2=$("<p></p>").text("Text."); // Create with jQuery
var txt3=document.createElement("p"); // Create with DOM
txt3.innerHTML="Text.";
$("p").append(txt1,txt2,txt3); // Append the new elements
}
In above code I've created paragraphs using three different techniques. I want to know which one is faster & more efficient in phonegap?
Upvotes: 0
Views: 1600
Reputation: 5052
The fastest among these is :
var txt3=document.createElement("p"); // Create with DOM
txt3.innerHTML="Text.";
Because when you use JQuery to append any element, it traverses through the entire DOM to search for the particular ID you want to append , While using native JS , it will traverse till it finds the 1st occurance of the element where you want to append.
EG:
<div id="a">
<div id="b">
<div id="c"></div>
</div>
</div>
Suppose you want to append some text in "b", JQuery will traverse till "c" while native JS will traverse only till "b" [the first instance of that ID]
Upvotes: -1
Reputation: 173642
var txt1="<p>Text.</p>"; // Create element with HTML
// actually: $('<p>Text.</p>');
In this case, jQuery will create a <div>
element, then set its .innerHTML
property to the HTML string you've passed. This is not particularly fast.
var txt2=$("<p></p>").text("Text."); // Create with jQuery
This is much faster, because jQuery is optimized to map this straight to createElement()
and you're using .text()
so no additional parsing is required.
var txt3=document.createElement("p"); // Create with DOM
txt3.innerHTML="Text.";
This sidesteps some parts of the two approaches and should be faster, but isn't because you're using .innerHTML
which has to get parsed first.
The fastest would be this:
var txt4 = document.createElement('p');
txt4.textContent = 'Text.';
Note that when I say fast, it's based on the results of this particular test case; normally you wouldn't get to a point where this would matter. Also, the native version is so much faster that a separate test would have to be done to get more accurate results for the other test cases :)
Upvotes: 7