4 possible ways of creating HTML elements (like a DIV) using jQuery are :
var newEle = $(document.createElement('div'));
var newEle = $('<div>');
var newEle = $('<div></div>');
var newEle = $('<div/>');
After performing a test to create HTML Elements using jQuery as Owen suggested, here were the results. I have clubbed all the 4 tests here for better readibility. However you should run each test for every new way of creating elements, individually.
Test
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
var counter = 5000;
var startTime = new Date().getTime();
// First Test
for (i = 0; i < counter; ++i) {
var newEle = $(document.createElement('div'));
}
var endTime = new Date().getTime();
alert(endTime - startTime);
// Second Test
var counter = 20000;
var startTime = new Date().getTime();
for (i = 0; i < counter; ++i) {
var newEle = $('<div>');
}
var endTime = new Date().getTime();
alert(endTime - startTime);
// Third Test
var counter = 20000;
var startTime = new Date().getTime();
for (i = 0; i < counter; ++i) {
var newEle = $('<div></div>');
}
var endTime = new Date().getTime();
alert(endTime - startTime);
// Fourth Test
var counter = 20000;
var startTime = new Date().getTime();
for (i = 0; i < counter; ++i) {
var newEle = $('<div/>');
}
var endTime = new Date().getTime();
alert(endTime - startTime);
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
Results:
The fastest way to create an HTML element using jQuery is using :
var newEle = $(document.createElement('div'));
The slowest one was :
var newEle = $('<div></div>');
In the text above you wrote
ReplyDeletevar newEle = $(document.createElement('div'));
but in the code there is:
var newEle = $(document.createElement('<div>'));
which one is correct?
That was a typo. Corrected. Thanks.
ReplyDeletevar newEle = $(document.createElement('<div>'));
ReplyDeleteIn your code you loop through the 1st test only 5000 instead of 20000 times as in the other tests.
Still the above is the fastest also when looped 20000 times.
Is there any way similar to DOMElement as in php. Could someone post a tutorial for the same?
ReplyDelete