ccxvii / mujs

An embeddable Javascript interpreter in C.
http://mujs.com/
ISC License
812 stars 98 forks source link

array join: avoid strcat, speedup from O(N^2) to O(N) #157

Closed avih closed 2 years ago

avih commented 2 years ago

Previously, each iteration (except the 1st) did this amount of calls: 2x strlen(result-so-far) + 2x strlen(element) + strlen(sep) Where except one strlen(element) they're implicit inside strcat, and of sizes which we already know.

Now each iteration does one strlen(element), and no strcat.

The big speedup is avoiding strlen of the result so far (twice) on each iteration - O(N^2), but the other extra 2x strlen can add up too.

Join of an array of 2000 strings of 80 chars each: Windows: before: 80ms, after: 2ms Linux: before: 20ms, after: 2ms Measured using Date.now()

avih commented 2 years ago

For reference, my test program (a bit more than 80 chars per element...):

var s = "x";
while (s.length < 80)
    s = s + s;

var a = []
for (var i = 0; i < 2000; i++)
    a.push("" + i + " " + s);

var t0 = Date.now()
a = a.join("\n");
print("ms: " + (Date.now() - t0));