473,395 Members | 1,422 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,395 software developers and data experts.

String concatenation performance

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
9 5736
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
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
"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
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
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
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
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

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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Jonas Galvez | last post by:
Is it true that joining the string elements of a list is faster than concatenating them via the '+' operator? "".join() vs 'a'+'b'+'c' If so, can anyone explain why?
37
by: Kevin C | last post by:
Quick Question: StringBuilder is obviously more efficient dealing with string concatenations than the old '+=' method... however, in dealing with relatively large string concatenations (ie,...
14
by: Bob | last post by:
I have a function that takes in a list of IDs (hundreds) as input parameter and needs to pass the data to another step as a comma delimited string. The source can easily create this list of IDs in...
33
by: genc_ymeri | last post by:
Hi over there, Propably this subject is discussed over and over several times. I did google it too but I was a little bit surprised what I read on internet when it comes 'when to use what'. Most...
12
by: Richard Lewis Haggard | last post by:
I thought that the whole point of StringBuilder was that it was supposed to be a faster way of building strings than string. However, I just put together a simple little application to do a...
87
by: Robert Seacord | last post by:
The SEI has published CMU/SEI-2006-TR-006 "Specifications for Managed Strings" and released a "proof-of-concept" implementation of the managed string library. The specification, source code for...
34
by: Larry Hastings | last post by:
This is such a long posting that I've broken it out into sections. Note that while developing this patch I discovered a Subtle Bug in CPython, which I have discussed in its own section below. ...
15
by: James | last post by:
Which is better, which is faster, which is easier etc... ????? String.Format ( "yadda {0} yadda {1}", x, y ) "yadda" + x.ToString() + " yadda" + y.tostring(); My code has a mish mash of...
3
by: Author | last post by:
I have always been wondering if there is any significant different between doing System.Console.WriteLine("Employee Name = " + employee.FirstName + " " + employee.LastName); and ...
34
by: raylopez99 | last post by:
StringBuilder better and faster than string for adding many strings. Look at the below. It's amazing how much faster StringBuilder is than string. The last loop below is telling: for adding...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

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.