473,320 Members | 1,732 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Javascript String Concatenations

I just read a great article by Dave Johnson on comparative performance
of XML and JSON parsing. It is a very important for anyone doing AJAX.

But the parsing is not the only place where CPU can be wasted. I
personally consider String Concatenations to be even bigger evil.

Here is test study that shows dramatic performance impact of String
Concatenations and how to avoid it.

http://www.softwaresecretweapons.com...gConcatenation

Nov 30 '05 #1
5 8577
ps******@outplay.com writes:
Here is test study that shows dramatic performance impact of String
Concatenations and how to avoid it.

http://www.softwaresecretweapons.com...gConcatenation


The author hints at the better solution, but doesn't elaborate.
In Javascript, a simple array can take the place of the Java StringBuffer,
so each "append" is a "push" and the "toString" is "join", i.e.,

var buf = [];
for(...long loop...) {
buf.push("string to append");
}
... buf.join("");

You can also try to hide this in a StringBuffer-like object:
---
function StringBuffer() {
this.buffer = [];
}
StringBuffer.prototype.append = function append(string) {
this.buffer.push(string);
return this;
};
StringBuffer.prototype.toString = function toString() {
return this.buffer.join("");
};

alert(new StringBuffer().append("hello ").append("world"));
---

It is so simple that there is no reason *not* to go for the general
solution instead of the stopgap measure of intermediate buffers
(ofcourse, if you know the size of your data, you can check that
intermediate buffers will do, but the time complexity is still
quadratic in the size of the outer loop - it's just the constant
that got smaller).

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Nov 30 '05 #2

ps******@outplay.com wrote:
I just read a great article by Dave Johnson on comparative performance
of XML and JSON parsing. It is a very important for anyone doing AJAX.

But the parsing is not the only place where CPU can be wasted. I
personally consider String Concatenations to be even bigger evil.

Here is test study that shows dramatic performance impact of String
Concatenations and how to avoid it.

http://www.softwaresecretweapons.com...gConcatenation


I would argue that test study is not conclusive. True, string
concatenations can be slow, but how you use them will also affect
performance. In the test study show, you're building a table.
Obviously it would be slow. Have you considered other factors? The
code is no doubt inefficient. For example, it is using two for loops!
That's a O(n^2). Don't forget the initialization of a for loop. Oh
yeah, did you miss the post increment? Would be more efficient if it
was a pre-increment instead. Unless you have written an optimized
code, that study does not accurately show the performance impact of
string concatenations just because there are other factors that are
heavily weighed in (to me anyways).

Nov 30 '05 #3
"web.dev" <we********@gmail.com> writes:
I would argue that test study is not conclusive. True, string
concatenations can be slow, but how you use them will also affect
performance. In the test study show, you're building a table.
Obviously it would be slow.
Why would it be slower than some other string of similar length?
Have you considered other factors? The code is no doubt
inefficient.
Apart from the string contcatenation, there are nothing that really
makes a difference.
For example, it is using two for loops! That's a O(n^2).
Well, no. The table has COLS*ROWS cells. Whether in one loop or
two, you have to create that many td-elements. If anything, that
number should be your "n" for complexity analysis.
Don't forget the initialization of a for loop.
Yes, it has overhead, but it's negligable.
A coprehensive test would also do a run of the loop without any
content, to find the overhead of that, but it is linear in n,
and with O(n^2) time for string doing n string concatenations,
that's quickly ignorable.
Oh yeah, did you miss the post increment? Would be more efficient
if it was a pre-increment instead.
You have absolutely no way of knowing that. The interpreter can easily
optimize a post increment where the value isn't used into a simple
increment. And again, even if it doubles the time taken for the increment,
it is still only a constant factor.
Unless you have written an optimized code, that study does not
accurately show the performance impact of string concatenations just
because there are other factors that are heavily weighed in (to me
anyways).


It doesn't really matter whether the surrounding code is optimized,
as long as you time it independently and subtract that from the total.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Nov 30 '05 #4
zif
web.dev wrote:
[...]
Unless you have written an optimized
code, that study does not accurately show the performance impact of
string concatenations just because there are other factors that are
heavily weighed in (to me anyways).


If the point is to test the performance of concatenation against some
other method, then the code for each block should be identical except
for the concatenation and its alternative.

It is the performance of the concatenation that is being tested, not the
surrounding code.
--
Zif
Nov 30 '05 #5
ps******@outplay.com wrote:
I just read a great article by Dave Johnson on comparative performance
of XML and JSON parsing. It is a very important for anyone doing AJAX.

But the parsing is not the only place where CPU can be wasted. I
personally consider String Concatenations to be even bigger evil.

Here is test study that shows dramatic performance impact of String
Concatenations and how to avoid it.
It also shows that some browsers don't have a problem with it.

http://www.softwaresecretweapons.com...gConcatenation


I'm not sure that concatenation per se is tested at all. '+=' is a
compound assignment (ECMA spec section 11.13.2), it may well be that IE
has a less than optimal algorithm for evaluating it.

Regardless, IE's woeful performance is not reflected in other browsers.
Firefox will perform += concatenation just as fast as the suggested
array push/join alternative (whether implemented in a 'StringBuffer'
object or simply coded instead of += ).

Using += IE takes around 40 times longer than array push/join. Its
array push/join is on par with Firefox.
--
Rob
Dec 1 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Wade G. Pemberton | last post by:
Can't find it quickly in the reference books.
3
by: Peter | last post by:
Hi, I try to make up a javascript string which contains numeric numbers in any positions. For example, I want to make a string: secretcode, where secretcode.charAt(0)==(-21),...
0
by: Garth17 | last post by:
This totally surprised me. I'm using IE 6. I built a really simple test.aspx page that had a javascript block in it like this: <script language=javascript src="spanish.js"></script> Inside...
0
by: gauthier | last post by:
Excuse me for a so simple question, but is there any method in the framework that encode strings as javascript string ie: "it's 9 o'clock" should be encoded as "it\'s 9 o\'clock" What I need...
8
by: Pavils Jurjans | last post by:
Hello, I have been developing an Ajax-style framework for couple of years now. Now I am reworking some parts of it. The problem was that I used to use JSON for JavaScript value...
4
by: Michael Bohman | last post by:
Hi I have a problem, on my page (*.aspx) i have a string written on klients computer in javascript. How can i pass this string to the codebehind *.cs file? From there i want to store it to a...
1
by: Chris | last post by:
Hi, This is a very basic problem, but i am not able to solve it. msgStr = "<script language =javascript>alert('An exception abc occured')</script>" Page.RegisterStartupScript("exception",...
7
by: deepthi230 | last post by:
how can i convert a javascript string to xml string?
3
by: Sanjay | last post by:
Hi Everyone, I am converting an image file into a Java string (via an applet) and would like to pass the Java string back to the Javascript function that calls the applet's. I know the simple...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.