我决定以一种基本的JavaScript名称空间模式来测试DOM缓存的性能,该模式在每天进行编码时会大量使用。 2013年10月4日更新:我在循环中添加了一些基本逻辑。 更新了jsfiddle和更新了jsperf 。
使用DOM缓存时,您可以将速度性能提高76%(基于每秒的操作)。
这是jsperf性能测试的全部结果-成对分组。 因此,将1与2比较,将3与4比较,依此类推...
结果表明,缓存DOM元素可以大大提高代码执行速度。 比较测试3和4可以清楚地看出这一点,您可以将每秒32,889次操作提高到602,620次操作!
计算百分比增加。
比较2a和2b显示速度提高了76%(基于每秒的操作数)。 ((98,072-23,358)/ 98,072)* 100 =增加76.18%。
一些基本的标记。
- list
- nested 1
- nested 2
- nested 3
- list
- list
- list
具有一些缓存的基本js对象。
MY_OBJECT =
{
cache: {},
init: function()
{
this.cache.c = $('#container');
this.cache.n = this.cache.c.find('.nested');
this.cache.s = this.cache.c.find('#status');
}
}
MY_OBJECT.init();
一些标准测试。
//no cache container find
$.each($('#container').find('li'), function(i,v)
{
//...
});
//cache container find
$.each(MY_OBJECT.cache.c.find('li'), function(i,v)
{
//...
});
//no cache class elements loop
$.each($('.nested'), function(i,v)
{
//...
});
//cache class elements loop
$.each(MY_OBJECT.cache.n, function(i,v)
{
//...
});
//no cache update status
$('.nested').each(function(i,v)
{
$('#status').text($(this).text());
});
//cache update status
$.each(MY_OBJECT.cache.n, function(i,v)
{
MY_OBJECT.cache.s.text($(this).text());
});
From: https://www.sitepoint.com/jquery-performance-dom-caching/