javascript - jq 中attr、prop、data的执行效率到底哪个好些?
问题描述
最后,从性能上对比,.prop() > .data() >.attr(),不同浏览器不同版本.data()和.attr()的性能关系有差异,不过.prop()总是最优的。
网上都是这么说的,但是我测出来为什么不是这样子的?(chrome:版本 57.0.2950.5)
<div id="header" data-id="header">
头部html
</div>
<script>
console.time('d');
$('#header').prop('id');
console.timeEnd('d');
console.time('a');
$('#header').data('id');
console.timeEnd('a');
console.time('b');
$('#header').attr('id');
console.timeEnd('b');
console.time('c');
document.getElementById('header');
console.timeEnd('c');
</script>
d: 0.359ms
(index):35 a: 0.602ms
(index):39 b: 0.346ms
(index):44 c: 0.0220ms
原因很简单,
prop() 是对一个对象的属性进行操作,和 JS 操作对象属性的区别不大。
data() 是 jQuery 自行封装的一层数据缓存逻辑(2.x 和 3.x 有点不一样,3.x 还带有 data-attr 的操作)。
attr() 是操作 DOM 属性的,浏览器除了执行 JS 处理逻辑,还需要执行 HTML Parser。
所以 prop > data > attr
至于为什么测试用例不准确,是因为这种微小差异,会被浏览器当时的其他情况影响导致测试结果出现偏差。
这种级别的代码优化,平时需求实现的时候不用太在意,只是在开发库、框架这一层面的代码才需要注意。
补充下 jQuery 实现的细节
prop
// 伪代码
prop: function( elem, name, value ) {
if ( value !== undefined ) {
return ( elem[ name ] = value );
}
return elem[ name ];
},
实际代码是 elem[name] = value
,只是一个对象属性赋值。
https://github.com/jquery/jqu...
data
// 伪代码
set: function( owner, data, value ) {
var prop,
cache = this.cache( owner );
// Handle: [ owner, key, value ] args
// Always use camelCase key (gh-2257)
if ( typeof data === "string" ) {
cache[ jQuery.camelCase( data ) ] = value;
// Handle: [ owner, { properties } ] args
} else {
// Copy the properties one-by-one to the cache object
for ( prop in data ) {
cache[ jQuery.camelCase( prop ) ] = data[ prop ];
}
}
return cache;
},
实际代码,cache[jQuery.camelCase(data)] = value
,也是对象属性赋值,不过整个 $.data()
的函数调用栈相比 $.prop()
要深,所以会慢一点点。
https://github.com/jquery/jqu...
attr
// 伪代码
attr: function( elem, name, value ) {
if ( value !== undefined ) {
elem.setAttribute( name, value + "" );
return value;
}
ret = jQuery.find.attr( elem, name );
// Non-existent attributes return null, we normalize to undefined
return ret == null ? undefined : ret;
}
实际代码,elem.setAttribute(name, value + "")
,这就不仅仅是 JS 操作了,动了 DOM 的东西,浏览器要跑一次 DOM 处理相关的。
https://github.com/jquery/jqu...
这篇关于javascript - jq 中attr、prop、data的执行效率到底哪个好些?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!