Skip to content

Instantly share code, notes, and snippets.

@hussaintamboli
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hussaintamboli/7d78849a0915496e7ae6 to your computer and use it in GitHub Desktop.
Save hussaintamboli/7d78849a0915496e7ae6 to your computer and use it in GitHub Desktop.
jQuery: adding <input> elemnts to a div. 1. by adding tags 2. by adding input elements. Which way is faster? Also This code seems to run in lesser time in Google Chrome than Firefox. Why? You can test it in jsbin.com
<html><head>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(function ($) {
// code1
var start = +new Date();
var html = '';
for (var i = 0; i < 1000; i++) {
$('#container1').append('<input name="text' + i + '"' + ' value="' + i + '" />');
}
var end = +new Date();
var diff = end - start;
console.log('time taken by code1 ' + diff + 'ms');
// code2
var start = +new Date();
var html = '';
for (var i = 0; i < 1000; i++) {
$('<input>').attr({
type: 'text',
id: 'foo' + i,
value: i
}).appendTo('#container2');
}
var end = +new Date();
var diff = end - start;
console.log('time taken by code2 ' + diff + 'ms');
});
</script>
</head><body>
<div id="container1"></div>
<div id="container2"></div>
</body></html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment