javascript - jQuery 性能 : Chain appends or append multiple arguments?

标签 javascript jquery performance append

我想知道其中哪一个性能更高,更重要的是为什么

$('a').append(
    $('<b></b>').text('1'),
    $('<b></b>').text('2'),
    $('<b></b>').text('3'));

$('a')
    .append($('<b></b>').text('1'))
    .append($('<b></b>').text('2'))
    .append($('<b></b>').text('3'));

哪里a<b>是任意选择器和标签。据我通过试用发现,它们的功能完全相同。

相关问题:What is the best way to add options to a select from as a JS object with jQuery?

编辑:

我问这个问题的原因是想知道我是否应该将 append 结构构造为:

texts = ['1','2','3','4','5'];
$a = $('a');
$a.append(...texts.map(function(o){ return $('<b></b>').text(o); }));

或如:

texts = ['1','2','3','4','5'];
$a = $('a');
for (o in texts) {
    $a.append($('<b></b>').text(o));
}

后一种更直观,我相信大多数程序员会选择编写它,因为前一种表现更好。

最佳答案

您可以使用基准测试工具来测试这一点。我使用了 JSPerf:https://jsperf.com/so-question

enter image description here

结果表明第一种情况要快得多。我相信这是因为每次调用与元素一起使用的函数(即 .append())时,jQuery 都会执行大量初始化、检查和兼容性工作。

第一种情况仅调用 .append() 一次,而第二种情况调用 .append() 三次。一般来说,函数调用越少,代码速度就越快。

关于javascript - jQuery 性能 : Chain appends or append multiple arguments?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49991927/

相关文章:

javascript - 如何正确地让 mock 在 Jest 中抛出错误?

javascript - 网站预加载器

performance - 与标量相比,SIMD 的按位与慢

performance - Julia 的特征分解比 Mathematica 慢 5 倍?

performance - Ubuntu 中的 OpenMP : parallel program works on double core processor in two times slower than single-threaded. 为什么?

javascript - 为了获得多维数组,在字符串中拆分字符串的一般解决方案是什么?

javascript - 访问 YUI 表中的嵌套 JSON

javascript - 如何从 JS 类中设置的 addEventListener 调用变量?

javascript - PHP 在服务器上调整图像大小并通过 ajax 返回

javascript - tinyscrollbar 内的 Accordion