Re: Building HTML - String vs Array
- From: "Evertjan." <exjxw.hannivoort@xxxxxxxxxxxx>
- Date: 10 Feb 2008 09:43:05 GMT
wrote on 10 feb 2008 in comp.lang.javascript:
On Feb 9, 5:15 am, RobG <rg...@xxxxxxxxxxxx> wrote:
On Feb 9, 12:13 pm, Java script Dude <despam2...@xxxxxxxx> wrote:
When building HTML in JavaScript when using JS DOM
(document.createElement(strType)) is not effective, there are
basically two methods for doing this:
1) Concatenate Strings:
var s="";
s+="<some_html>";
s+="<some_more_html>"//...
someElem.innerHTML=s
~
2) Build Using Arrays:
var a=[];
a.push("<some_html>");
a.push("<_more_html>");
someElem.innerHTML=a.join("")
~
I have reviewed code from several enterprise JavaScript based sites
and find a mixture of both methods.
Doing some simple performance testing I found that Internet Explorer
is ~3 faster with Arrays than Strings. Mozilla is ~2.5 times faster
with Strings than Arrays.
Has anybody done similar tests and what were your results and your
decision for your applications.
The real issue is that IE is painfully slow using the += compound
operator. Instead use something like:
s = s + someHTML;
Use either arrays or string concatenation, whichever suits.
--
Rob
Hello Rob,
I tried using IE 6 and += seems to be faster than s = s + "xxx".
Here is the performance test I am doing:
<html>
<head>
<title>String Build Performance Tester</title>
<script>
function doTest(){
var
iItr=10000,sHtml="",iSWS1
,iSWD1,iSWS2,iSWD2,iSWS3,iSWD3
,aHtml=[]
;
sHtml=""
iSWS1 = (new Date()).getTime()
for(var i=0;i<iItr;i++){sHtml+=__()}
iSWD1 = (new Date()).getTime()
sHtml=""
iSWS2 = (new Date()).getTime()
for(var i=0;i<iItr;i++){sHtml=sHtml+__()}
iSWD2 = (new Date()).getTime()
sHtml=""
iSWS3 = (new Date()).getTime()
for(var i=0;i<iItr;i++){aHtml.push(__())}
sHtml=aHtml.join()
iSWD3 = (new Date()).getTime()
alert(
"Test Results:"
+"\n. Concat 1 (+=) = "+((iSWD1-iSWS1)/1000)+"s"
+"\n. Concat 2 (s=s+) = "+((iSWD2-iSWS2)/1000)+"s"
+"\n. Array Join = "+((iSWD3-iSWS3)/1000)+"s"
)
function __(){ return new String(Math.random())}
}
</script>
</head>
<body>
<script>doTest()</script>
If you change the above line to:
<button onclick='doTest()'>do test</button>
and do the test repeatedly [IE7],
you will see that sometimes concat1 is faster, sometimes concat2,
while join is the big, big looser.
Ubder FF@ this is the same,
but here they are both faster than the array join!!!
</body>
</html>
~end code~
--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
.
- References:
- Building HTML - String vs Array
- From: Java script Dude
- Re: Building HTML - String vs Array
- From: RobG
- Re: Building HTML - String vs Array
- From: tim . c . quinn
- Building HTML - String vs Array
- Prev by Date: <FAQENTRY>4.9 code change</FAQENTRY>
- Next by Date: Re: Strange javascript in my index.html file.
- Previous by thread: Re: Building HTML - String vs Array
- Next by thread: Re: Building HTML - String vs Array
- Index(es):