简体   繁体   English

为什么星号金字塔JSPerf测试的测试用例2需要这么长时间?

[英]Why does test case 2 of the asterisk pyramid JSPerf test take so long?

var elemText = document.getElementById("insert");
for (var k = 1; k <= 4; k++) {
  for (var j = 1; j <= k; j++) {
    elemText.innerHTML += ('*');
  };
  elemText.innerHTML += ('<br>');
};

Teardown: 拆除:

document.getElementById("insert").innerHTML = "";

Is there a coding error? 有编码错误吗? Is is just horribly inefficient (I think this unlikely to be the sole reason)? 效率极低吗(我认为这不可能是唯一的原因)? Is it something to do with the way the test is set up? 与测试的设置方式有关吗?

Is there a coding error? 有编码错误吗?

Yes. 是。 You forgot to reinitialize the <div> in test #2. 您忘记了在测试2中重新初始化<div> You need to empty it, just as you set result = [] in test #1. 您需要清空它,就像在测试#1中设置result = [] Doing it in the teardown is not enough, and test #2 will generate much longer texts before clearing than test #1. 仅在拆解中进行测试还不够,并且测试#2在清除之前会比测试#1生成更长的文本。

Also, your test cases have not the same result. 同样,您的测试用例也有不同的结果。 Since you want to output <br /> elements in test #1 as well, you would need to use innerHTML there, too. 由于您还希望在测试#1中输出<br />元素,因此您也需要在其中使用innerHTML Your current code did output <br> literally as text. 您当前的代码确实将<br>输出为文本。

Improved test setup 改进的测试设置

Is is just horribly inefficient? 效率低下吗?

Yes. 是。 Working with innerHTML is inefficient - it needs the HTML parser each time you assign to it, and you are doing it very often. 使用innerHTML效率低下-每次分配给它时都需要HTML解析器,而且您经常这样做。 Also, since you are using += it needs to serialize the DOM each time. 另外,由于您使用的是+=因此每次都需要序列化DOM。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM