By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,843 Members | 2,311 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,843 IT Pros & Developers. It's quick & easy.

String concatenation performance

P: n/a
In many languages, it is necessary to string together multiple strings
into one string for use over multiple lines of code.

Which one is the most efficient from the interpreters perspective:

Case 1:
str += '<?xml version="1.0" encoding="' + charset + '"?>\n';
str += '<view-source-with version="1.1">\n';
str += ' <default-item-index>' + this.defaultItem +
'</default-item-index>\n';
str += ' <show-frame-warning>' + this.frameWarning
+'</show-frame-warning>\n';

Case 2:
str = '<?xml version="1.0" encoding="' + charset + '"?>\n'+
'<view-source-with version="1.1">\n'+
' <default-item-index>' + this.defaultItem +
'</default-item-index>\n'+
' <show-frame-warning>' + this.frameWarning
+'</show-frame-warning>\n'+
...

Case 1 is the most common but case 2 is my personal preference. It
takes less code to write but I'm not sure how effective it is when it
reaches the language optimization and interpreter.

Any ideas which is better from a raw interpreter performance
perspective?

JsD

Sep 20 '05 #1
Share this Question
Share on Google+
9 Replies


P: n/a
Java script Dude said the following on 9/19/2005 9:29 PM:
In many languages, it is necessary to string together multiple strings
into one string for use over multiple lines of code.

Which one is the most efficient from the interpreters perspective:

Case 1:
str += '<?xml version="1.0" encoding="' + charset + '"?>\n';
str += '<view-source-with version="1.1">\n';
str += ' <default-item-index>' + this.defaultItem +
'</default-item-index>\n';
str += ' <show-frame-warning>' + this.frameWarning
+'</show-frame-warning>\n';

Case 2:
str = '<?xml version="1.0" encoding="' + charset + '"?>\n'+
'<view-source-with version="1.1">\n'+
' <default-item-index>' + this.defaultItem +
'</default-item-index>\n'+
' <show-frame-warning>' + this.frameWarning
+'</show-frame-warning>\n'+
...

Case 1 is the most common but case 2 is my personal preference. It
takes less code to write but I'm not sure how effective it is when it
reaches the language optimization and interpreter.

Any ideas which is better from a raw interpreter performance
perspective?


It's easy enough to test and raw performance will depend on the
interpreter in use. You will get different results in different
environments. Just guessing, I would guess Case 2 to be slightly quicker
because it is simply adding strings, not adding strings to another
string. Case 1 would seem to need to look up str each time and thus
cause more overhead time.

Put both cases in a for..loop with a timer and loop them both about
10,000 times and you will see which is faster though.

--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Sep 20 '05 #2

P: n/a
Java script Dude wrote:
In many languages, it is necessary to string together multiple strings
into one string for use over multiple lines of code.

Which one is the most efficient from the interpreters perspective:

Case 1:
str += '<?xml version="1.0" encoding="' + charset + '"?>\n';
str += '<view-source-with version="1.1">\n';
str += ' <default-item-index>' + this.defaultItem +
'</default-item-index>\n';
str += ' <show-frame-warning>' + this.frameWarning
+'</show-frame-warning>\n';

Case 2:
str = '<?xml version="1.0" encoding="' + charset + '"?>\n'+
'<view-source-with version="1.1">\n'+
' <default-item-index>' + this.defaultItem +
'</default-item-index>\n'+
' <show-frame-warning>' + this.frameWarning
+'</show-frame-warning>\n'+
...

Case 1 is the most common but case 2 is my personal preference. It
takes less code to write but I'm not sure how effective it is when it
reaches the language optimization and interpreter.

Any ideas which is better from a raw interpreter performance
perspective?


Why don't you just test it? Run a loop a few thousand times to see
which one is faster (I think you'll find there's no difference). Unless
you are writting hundreds of lines of code, it will likely make no
perceptible difference.

However, I think you will find joining an array to be the fastest method
of all:

Case 3:

str = [
'<?xml version="1.0" encoding="',
charset,
'"?><view-source-with version="1.1">',
'<default-item-index>',
this.defaultItem,
'</default-item-index>\n',
' <show-frame-warning>',
this.frameWarning,
'</show-frame-warning>'
];

alert( str.join('') );

--
Rob
Sep 20 '05 #3

P: n/a
"Java script Dude" <de********@yahoo.ca> wrote in message
news:11********************@o13g2000cwo.googlegrou ps.com...
In many languages, it is necessary to string together multiple strings
into one string for use over multiple lines of code.

Which one is the most efficient from the interpreters perspective:


With samples this small I doubt you could ever measure a difference even on
a slow computer.

You could try to discover a difference by:

1) Creating much larger samples.

This can be informative but isn't conclusive. Many interperters are
otpimized for "real world" information: performance often doesn't scale
regularly as you increase the size of the data being worked with.

2) Running the sample many times via an internal loop.

The idea here is to write a JavaScript program that loops over your code
many, many times until a difference can be measured.

This can also be informative but again isn't conclusive. When you start
doing tasks large numbers of times you get into performance issues that may
not be associated with the task at hand: loop efficiency, memory leaks, etc.

3) Running the sample many times via an external loop.

The idea here to run the sample many times using some external manager.
You'd do this to try and measure the "real" code, not an artificial version
of it.

However this also has some issues. Namely the fact that the code is running
in a container and that container is using system resources along with the
process that's managing the test. The container may have issues with
repeated accesses (opening the same web page again and again and again in a
browser, for example, often results in increased memory usage).

Lastly you're talking about JavaScript... but "JavaScript" doesn't define an
interpreter, it's a spec. What's fast in one implementation may be dog slow
in another. So any tests you construct really have to be implementation
specific.

I would plan to do multiple examples of each kind of test I mentioned (and
perhaps others) and attempt to collate the results into something useful.
You'd have to run the tests many, many times (switching the order of the
testing) to ensure that the external resource consumption issues are
minimized as much as possible.

I don't have an answer to your question, I'm afraid... but it would neat to
figure out. However in the end my gut (and if you'd seen my gut you'd know
it's not something you can easily ignore) says that in any real-world
application the difference will be negligible. My general advice is to
build what's easiest to understand and maintain first - then IF there's a
performance issue, find some places to tighten up.

(Sorry - I didn't plan to veer off on a lecture there... the question is
definitely interesting. I tend to rattle on when I'm interested.)

Jim Davis
Sep 20 '05 #4

P: n/a
i would guess the string.concat method to be the quickest. i agree with
the others : the only way to be sure is to do a quick benchmark of the
different solutions.

cheers,

stephane.

Sep 20 '05 #5

P: n/a
Thanks all for your replys.

Looks like I will need to build a testing prototype and run it through
the paces. I will try all 4 techniques to see which comes out in first
place. I will also try to throw this against IE, Moz. I would assume
that the latter will be faster for this one.

Not sure how soon I will be able to build this but I'll try sometime
when I'm killing some time in a Cafe sometime soon.

JsD

Sep 20 '05 #6

P: n/a
JRS: In article <11********************@o13g2000cwo.googlegroups.c om>,
dated Mon, 19 Sep 2005 18:29:23, seen in news:comp.lang.javascript, Java
script Dude <de********@yahoo.ca> posted :
In many languages, it is necessary to string together multiple strings
into one string for use over multiple lines of code.

Which one is the most efficient from the interpreters perspective:

Case 1:
str += '<?xml version="1.0" encoding="' + charset + '"?>\n';
str += '<view-source-with version="1.1">\n';
str += ' <default-item-index>' + this.defaultItem +
'</default-item-index>\n';
str += ' <show-frame-warning>' + this.frameWarning
+'</show-frame-warning>\n';

Case 2:
str = '<?xml version="1.0" encoding="' + charset + '"?>\n'+
'<view-source-with version="1.1">\n'+
' <default-item-index>' + this.defaultItem +
'</default-item-index>\n'+
' <show-frame-warning>' + this.frameWarning
+'</show-frame-warning>\n'+
...

Case 1 is the most common but case 2 is my personal preference. It
takes less code to write but I'm not sure how effective it is when it
reaches the language optimization and interpreter.

Any ideas which is better from a raw interpreter performance
perspective?


charset = "ddd"
K = 8778

D0 = new Date()

J = K ; while (J--) {
str = ""
str += '<?xml version="1.0" encoding="' + charset + '"?>\n';
str += '<view-source-with version="1.1">\n';
str += ' <default-item-index>' +
'</default-item-index>\n';
str += ' <show-frame-warning>' +
+'</show-frame-warning>\n';
}

D1 = new Date()

J = K ; while (J--) {
str = '<?xml version="1.0" encoding="' + charset + '"?>\n'+
'<view-source-with version="1.1">\n'+
' <default-item-index>' +
'</default-item-index>\n'+
' <show-frame-warning>' +
+'</show-frame-warning>\n'
}

D2 = new Date()

J = K ; while (J--) {
str = ['<?xml version="1.0" encoding="' + charset + '"?>\n',
'<view-source-with version="1.1">\n',
' <default-item-index>' ,
'</default-item-index>\n',
' <show-frame-warning>' ,
+'</show-frame-warning>\n' ]
str.join("")
}

D3 = new Date()

X = [D3-D2, D2-D1, D1-D0] // RESULT typically 1210,660,930 for me.
That's reasonable, since the best way just says what is to be done,
without detailing a mechanism. Results may differ with other systems.

--
John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Sep 20 '05 #7

P: n/a
Dr John Stockton wrote:
JRS: In article <11********************@o13g2000cwo.googlegroups.c om>,
dated Mon, 19 Sep 2005 18:29:23, seen in news:comp.lang.javascript, Java
script Dude <de********@yahoo.ca> posted :
In many languages, it is necessary to string together multiple strings
into one string for use over multiple lines of code.

Which one is the most efficient from the interpreters perspective:

Case 1:
str += '<?xml version="1.0" encoding="' + charset + '"?>\n';
str += '<view-source-with version="1.1">\n';
str += ' <default-item-index>' + this.defaultItem +
'</default-item-index>\n';
str += ' <show-frame-warning>' + this.frameWarning
+'</show-frame-warning>\n';

Case 2:
str = '<?xml version="1.0" encoding="' + charset + '"?>\n'+
'<view-source-with version="1.1">\n'+
' <default-item-index>' + this.defaultItem +
'</default-item-index>\n'+
' <show-frame-warning>' + this.frameWarning
+'</show-frame-warning>\n'+
...

Case 1 is the most common but case 2 is my personal preference. It
takes less code to write but I'm not sure how effective it is when it
reaches the language optimization and interpreter.

Any ideas which is better from a raw interpreter performance
perspective?

charset = "ddd"
K = 8778

D0 = new Date()

J = K ; while (J--) {
str = ""
str += '<?xml version="1.0" encoding="' + charset + '"?>\n';
str += '<view-source-with version="1.1">\n';
str += ' <default-item-index>' +
'</default-item-index>\n';
str += ' <show-frame-warning>' +
+'</show-frame-warning>\n';
}

D1 = new Date()

J = K ; while (J--) {
str = '<?xml version="1.0" encoding="' + charset + '"?>\n'+
'<view-source-with version="1.1">\n'+
' <default-item-index>' +
'</default-item-index>\n'+
' <show-frame-warning>' +
+'</show-frame-warning>\n'
}

D2 = new Date()

J = K ; while (J--) {
str = ['<?xml version="1.0" encoding="' + charset + '"?>\n',
'<view-source-with version="1.1">\n',
' <default-item-index>' ,
'</default-item-index>\n',
' <show-frame-warning>' ,
+'</show-frame-warning>\n' ]
str.join("")
}

D3 = new Date()

X = [D3-D2, D2-D1, D1-D0] // RESULT typically 1210,660,930 for me.
That's reasonable, since the best way just says what is to be done,
without detailing a mechanism. Results may differ with other systems.


Results appear to be affected by the order in which the blocks are run
and (I guess) by optimisation that appears to introduce unpredictable
results.

Adopting the above order as C1, C2, C3, the following were achieved in
Firefox:

C1, C2, C3 => 1200, 360, 340

C1, C3, C2 => 313, 1359, 375

C3, C2, C1 => 360, 280, 1260

C2, C3, C1 => 375, 1310, 300

Results were similar in IE but two to three times faster. I have no
idea why say C3 takes four times longer when run second as opposed to
first - maybe some internal optimisation occurs that affects the
performance of individual blocks.

Below is a script that runs each block as a separate function. They can
be called in any order, the order still seems important but is less
significant than when all in one function. I guess each function should
be called using some random time displacement and setTimeout to make
them as independent as possible.

Times for Firefox 'plainConcat' are the same as for IE, but 'plusEquals'
and 'arrayJoin' take about twice as long. The following are examples of
the best (lowest) times achieved overall for various orders:

Order 1:
plainConcat: 94
plusEqual: 203
joinArray: 297

Order 2:
plainConcat: 94
joinArray: 546
plusEqual: 250

Order 3:
joinArray: 265
plusEqual: 157
plainConcat: 125
The variance for an individual method between each run is often greater
than that between each method: Jim's advice in his last paragraph is sound.
<script type="text/javascript">

var charset = "blah"

function plusEqual(n)
{
var str;
while (n--) {
str = ''
str += '<?xml version="1.0" encoding="';
str += charset + '"?>\n';
str += '<view-source-with version="1.1">\n';
str += ' <default-item-index>' + '</default-item-index>\n';
str += ' <show-frame-warning>' + '</show-frame-warning>\n';
}
return str;
}

function plainConcat(n)
{
var str;
while (n--) {
str = ''
+ '<?xml version="1.0" encoding="'
+ charset + '"?>\n'
+ '<view-source-with version="1.1">\n';
+ ' <default-item-index>' + '</default-item-index>\n';
+ ' <show-frame-warning>' + '</show-frame-warning>\n';
}
return str;
}

function joinArray(n)
{
var str;
while (n--) {
str = [
'<?xml version="1.0" encoding="',
charset,
'"?>\n',
'<view-source-with version="1.1">\n',
' <default-item-index>',
'</default-item-index>\n',
' <show-frame-warning>',
'</show-frame-warning>\n'
];
}
return str.join("")
}

function doInOrder()
{
var num = 10000;
var msg = [];
var st, ft;
for (var i=0, j = arguments.length; i<j; i++){
st = new Date();
window[arguments[i]](num);
ft = new Date();
msg[i] = arguments[i] + ': ' + (ft-st);
}

return msg;
}

</script>

<div id='xx'></div>

<script type="text/javascript">
var x = doInOrder(
'plainConcat'
,
'plusEqual'
,
'joinArray'
);
document.getElementById('xx').innerHTML = x.join('<br>');
</script>
--
Rob
Sep 21 '05 #8

P: n/a

The interpreter can do either and is oblivious of performance per se, what
you mean is using the resources efficiently without overheading much over
cpu cycles, Case 1 is easier for reading when editing, and is maintable by
prepending/appending to the latter/former line, for resource usage it
depends on the resource you're targetting, if a machine with lots of
cycles(server?) or very low on available memory(32mbs?), if it's a long
string, say 500chars or more, then I'd stick with Case 1, if shorter, then
Case2. Case2 is only good for a short string, it won't lean on the
resources per cpu cycle, then again, if the machine/environment has plenty
of available resources, it won't matter much.
Danny
Sep 23 '05 #9

P: n/a
I agree, if you app is very small, the performance hit on the CPU is
very small. But, I tend write massive workflow applications where I am
pushing as much html generation to JavaScript. My server side code
simply passes a very small HTML container specifying mainly JavaScript
libs, init code and application data sent down in JS data structures
like Arrays, JSON and the like.

With this style of application coding, it is necessary to have very
long template generation sequences like I've added to bottom of this
post.

As long as you indent your code properly and use brackets to nest
logic, it is very maintaintable and highly efficient. Actually reads
almost as well as a normal template file.

However, there is one drawback and that is errors can easilly happen if
you miss out on a `+` character. But if you are developing with Mozilla
(which anybody in their right mind should be doing), you can see the
error location very easy with Java Console.

I also code this way in Java which is still faster than using string
buffers and way faster than concatenating strings (bad programmer BAD)
:]

<snip>
dw(
"<div class=WizPanel id=FileSelect style='color: #444444'>"+
_GUI.buildCurveTable(
(
"<div class=T3B><u>Destination</u></div>"+
"<div class=Indent id=tfDestInfo></div>"+
"<div class=T3B><u>File Information</u></div>"+
"<div class=Indent>"+
"<table cellpadding=0 cellspacing=0 border=0 width=750
style='font: bold 14px arial; color: #444444'>"+
"<tr style='color: #444444'><td align=right>File:</td><td
id=tdFileName style='white-space: nowrap; font-style:
italic'>&nbsp;</td><td id=tdFileCheckin
width=100%>~1</td></tr>".format(bDebug?"Debug Mode: See Debug Ghost
Frame Window!":"<iframe name='FileCheckinWin' frameborder='0'
scrolling='no' style='width: 100px; height: 20px; border: 0px solid;
margin-right: 10px'></iframe><span id=spBrowseCom style='color:
navy'></span>")+
"<tr style='color: #444444'><td id=tfPath
align=right>Path:</td><td id=tdFilePath colspan=2 style='white-space:
nowrap'>&nbsp;</td></tr>"+
"<tr style='color: #444444'><td id=tfClass align=right>File
Classification:</td><td colspan=2>&nbsp;<input type=text class=text
id=tbClass size=60 readonly></td></tr>"+
"<tr style='color: #444444'><td id=tfDesc align=right>File
Description:</td><td colspan=2>&nbsp;<input type=text class=text
id=tbDesc size=60></td></tr>"+
"<tr style='color: #444444'><td id=tfUnlock
align=right>Un-lock: </td><td align=left colspan=2><input
type=checkbox class=checkbox id=cbUnlock style='border: 0px solid;
background: #dddddd'></td></tr>"+
"<tr style='color: #444444'><td id=tfRev align=right>(~1)
Revise File: </td><td align=left id=tfRev colspan=2><input
type=checkbox class=checkbox id=cbRev style='border: 0px solid;
background:
#dddddd'></td></tr>".format(wnAnc("ancRevise","?","font-size: 14px"))+
"<tr style='color: #444444'><td align=right id=tfRevCom
style='white-space: nowrap'>Revision Comment:</td><td
colspan=2>&nbsp;<input type=text class=text id=tbRevCom
size=60></td></tr>"+
//"<tr style='color: #444444'><td align=right id=tfRevCom
style='white-space: nowrap'>&nbsp;</td><td colspan=2><input type=button
class=button id=btFinish name=btFinish value='Finish ...'
style='margin-top: 3px; margin-left: 5px; margin-right: 0px;
width="+(is.ie?70:60)+"'></td></tr>"+
_GUI.buildCurveTable( "Submit File ...", { tableID:
"btFinish", tableProps: "", bgColor: "#999999", outerCSS: "height:
10px; margin: 10 0 0 350; cursor:"+(is.ie?"hand":"pointer"), innerCSS:
"font: bold 15px arial; color: white; padding: 3 4 3 4", filletPixels:
2, filletColor: "dddddd" })+
"</table>"+
"</div>"+
"<div id=divCommentBlock class=Indent></div>"
),
{ bgColor: "#dddddd", outerCSS: "margin: 0 0 0 5",
innerCSS: "padding: 2 2 2 2", filletPixels: 2, filletColor: "ffffef" }
)+
"</div>"+
.....
</snip>

Above may look scary but when properly layed out (no line breaks etc)
it is very readable and maintainable.

JsD

Sep 25 '05 #10

This discussion thread is closed

Replies have been disabled for this discussion.