p2p.wrox.com Forums

p2p.wrox.com Forums (http://p2p.wrox.com/index.php)
-   BOOK: Professional JavaScript for Web Developers ISBN: 978-0-7645-7908-0 (http://p2p.wrox.com/forumdisplay.php?f=174)
-   -   Chapter 3 - StringBuffer vs += Performance Issue (http://p2p.wrox.com/showthread.php?t=76758)

IAmCorbin October 26th, 2009 03:24 AM

Chapter 3 - StringBuffer vs += Performance Issue
 
I have just copied down the code for the StringBuffer "class" performance comparison on pgs 97-98 of the book but my results are opposite to what the book is explaining. The += operation without using the StringBuffer class is actually running significantly faster. Here is the code:

Code:

function StringBuffer1() {
        this._strings = new Array;

        if (typeof StringBuffer1._initialized == "undefined") {
                StringBuffer1.prototype.append = function (str) {
                        this._strings.push(str)
                };
                StringBuffer1.prototype.toString = function () {
                        return this._strings.join("");
                };
                StringBuffer1._initialized = true;
        };
};

function StringBuffer2() {
        this._strings = new Array;
};
StringBuffer2.prototype.append = function (str) {
        this._strings.push(str)
};
StringBuffer2.prototype.toString = function () {
        return this._strings.join("");
};




var d1 = new Date();
var str = "";
for (var i=0; i < 10000; i++) {
        str += "text";
}
var d2 = new Date();
document.write("Concatenation with plus: " + (d2.getTime() - d1.getTime()) + " milliseconds<br />");

var oBuffer = new StringBuffer1();
d1 = new Date();
for (var i=0; i < 10000; i++) {
        oBuffer.append("text");
}
var sResult = oBuffer.toString();
d2 = new Date();
document.write("Concatenation with StringBuffer1: " + (d2.getTime() - d1.getTime()) + " milliseconds<br />");

var oBuffer = new StringBuffer2();
d1 = new Date();
for (var i=0; i < 10000; i++) {
        oBuffer.append("text");
}
var sResult = oBuffer.toString();
d2 = new Date();
document.write("Concatenation with StringBuffer2: " + (d2.getTime() - d1.getTime()) + " milliseconds<br />");

results:
Concatenation with plus: 12 milliseconds
Concatenation with StringBuffer1: 23 milliseconds
Concatenation with StringBuffer2: 26 milliseconds

I do have the 2005 version of the text, so I don't know if something has been changed with javascript since this publication. I'm also using Firefox 3.0.14 right now.


All times are GMT -4. The time now is 05:31 PM.

Powered by vBulletin®
Copyright ©2000 - 2019, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.