Wk_of_Angmar
Wk_of_Angmar

Reputation: 572

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?

Upvotes: 0

Views: 118

Answers (1)

Bergi
Bergi

Reputation: 664930

Is there a coding error?

Yes. You forgot to reinitialize the <div> in test #2. You need to empty it, just as you set result = [] in test #1. Doing it in the teardown is not enough, and test #2 will generate much longer texts before clearing than test #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. Your current code did output <br> literally as text.

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. Also, since you are using += it needs to serialize the DOM each time.

Upvotes: 1

Related Questions