0

I'm trying to post an array that gets modified in a local web page of 672 elements back to the server. For this I put it in a string, seperated by comma's, in a Javascript like this:

    alert("begin");
    var sBsbData=""
    for (var x=0;x<24*4*7;x++)
        sBsbData = sBsbData + BsbData[x] + ',';

    alert(sBsbData);

BsbData is an array of int's; values don't exceed 10.

This is code that would get processed by any processor without a blink of an eye... yet it takes about ten seconds between the two alerts! What am I doing wrong here?? Did I pick a particularly bad concat method for this purpose?

5
  • 1
    Is there a specific reason you are not using BsbData.join(',')? But aside from that, the loop doesn't seem to take up any measurable time: jsfiddle.net/AUCWS. Commented Sep 6, 2013 at 10:02
  • Why don't you just use var sBsbData = BsbData.join(',');? Commented Sep 6, 2013 at 10:02
  • Did you try serializing the array into a string? You can simply write var sBsbData = BsbData.toString(), and the format will be the same (values separated by commas). Commented Sep 6, 2013 at 10:03
  • I know using ++x is slightly faster, but I don't think that's the problem. Commented Sep 6, 2013 at 10:04
  • @RomainBraun there is actually no difference on non-braindead engines like V8 and SpiderMonkey. Commented Sep 17, 2013 at 9:41

1 Answer 1

3

It is not slow - it's the alert that takes a while to be created (for some odd reason).

Proof of concept:

var BsbData = [];
for (var i = 0; i < 24 * 4 * 7; i++) {
    BsbData[i] = Math.round(Math.random() * 10);
}

console.log("begin");
alert("begin");

var sBsbData=""
for (var x=0;x<24*4*7;x++)
    sBsbData = sBsbData + BsbData[x] + ',';

console.log(sBsbData);
// !!! This is where the code will halt for a bit (the string has already been created) !!!
alert(sBsbData);

That said - you should just use var sBsbData = BsbData.join(',');

Sign up to request clarification or add additional context in comments.

7 Comments

Note that passing , to join() gives the exact same result as invoking toString() on the array, and may actually be slower.
@FrédéricHamidi Does the JS standard specify how an array should be returned if invoking toString, or could you risk having different results in different browsers? (eg 1,2,3 in Chrome, but 1, 2, 3 in IE?)
That's part of the spec, so the results will be consistent across browsers. I'll try to find a link.
@Felix, join() will be faster then. That's a pity, toString() looks more like a primitive operation than join() :)
@Frédéric: I think the .join method is defined such that if no argument is passed, , is used as separator.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.