Skip to content

Instantly share code, notes, and snippets.

@black-black-cat
Last active March 10, 2016 07:44
Show Gist options
  • Save black-black-cat/e419b5047f38be4c8b49 to your computer and use it in GitHub Desktop.
Save black-black-cat/e419b5047f38be4c8b49 to your computer and use it in GitHub Desktop.
测试jquery选择器速度
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title></title>
<style>
.table {
width: 800px;
height: 600px;
background-color: #fafafa;
margin: 36px auto;
}
table {
border-spacing: 0;
width: 100%;
border: 1px solid #ACACAC;
border-radius: 3px;
}
table > thead > tr > th {
word-break: break-all;
word-wrap: break-word;
border-bottom: 2px solid #ddd;
height: 30px;
vertical-align: bottom;
}
table > tbody > tr > td {
word-break: break-all;
word-wrap: break-word;
border-bottom: 1px solid #ddd;
height: 30px;
vertical-align: middle;
text-align: center;
}
table > thead > tr {
display: table-row;
vertical-align: inherit;
border-color: inherit;
}
table > tbody > tr {
display: table-row;
vertical-align: inherit;
border-color: inherit;
}
.update {
width: 66px;
padding-top: 4px;
padding-bottom: 4px;
border-radius: 3px;
margin: 6px auto;
color: #fff;
background-color: #369;
cursor: pointer;
}
</style>
</head>
<body>
<div class="table">
<table>
<thead>
<tr>
<th>用户名</th>
<th>性别</th>
<th>邮箱</th>
<th>地址</th>
<th>操作</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<script src="bower_components/jquery/dist/jquery.min.js"></script>
<script>
$(function() {
createList(function() {
updateListItem();
});
});
function createList(fn) {
$.get('http://localhost:63342/test01/querylist.json', function(info) {
var arr = info.result;
$.each(arr, function(i, obj) {
console.log(obj);
var name = obj.userName,
email = obj.email,
gender = obj.gender,
address = obj.address,
userId = obj.userId;
var strHtml = '<tr><td>'+name+'</td><td>'+gender+'</td><td>'+email+'</td><td>'+address+'</td><td><div class="update" name="'+userId+'">修改</div></td></tr>';
$('tbody').append(strHtml);
});
typeof fn == 'function' && fn();
})
}
function updateListItem() {
$('.update').on('click', function() {
var $this = $(this);
var userId = $this.attr('name');
$.get('http://localhost:63342/test01/querylist.json', function(info) {
$.each(info.result, function(i, obj) {
if(obj.userId === userId) {
console.log(obj);
}
})
})
})
}
function testSpeed(fn) {
var begin = new Date;
for (var i = 0; i < Math.pow(10, 5); i++) {
typeof fn === 'function' && fn();
}
var end = new Date;
console.log(end - begin);
}
testSpeed(function() {
$('table').find('tbody');
}); // -> 1920ms
testSpeed(function() {
$('table').children('tbody');
}); // -> 4911ms
testSpeed(function() {
$('table>tbody');
}); // -> 2170ms
testSpeed(function() {
$('table tbody');
}); // -> 2385ms
testSpeed(function() {
document.getElementsByTagName('table')[0].getElementsByTagName('tbody');
}); // -> 198ms
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment