Alfred
Alfred

Reputation: 61773

body += chunk will reallocate the entire response string every time a chunk arrives?

I was reading this article => http://mgutz.com/2010/10/01/check_gmail_with_node_js.html.

Below in the comments Shomrom says:

body += chunk will reallocate the entire response string every time a chunk arrives. I believe it would be much better to append each chunk to an array and do a .join() when you have all you need.

Does body += chunk really reallocate the entire response string every time a chunk arrives? If so, what is the best way to improve this snippet that we can print body as cheap possible?

It contains the following snippet:

var http = require('http');

var user = '[email protected]';
var password = 'password';
var auth = new Buffer(user + ':' + password).toString('base64');

var google = http.createClient(443, 'mail.google.com', true);
var request = google.request('GET', '/mail/feed/atom/', {
    'Host': 'mail.google.com', 
    'Authorization': 'Basic ' + auth 
});

request.addListener('response', function(res) {
    var body = '';    
    res.addListener('data', function(chunk) { 
        body += chunk;
    });
    res.addListener('end', function() { 
        console.log(body); 
    });
});

request.end();

Upvotes: 1

Views: 640

Answers (1)

Fred Foo
Fred Foo

Reputation: 363567

Not necessarily every time, but in general it may do so quite often (say half the time, depending on the length of your strings and the implementation of JavaScript). Using an array and join is a good recommendation:

var bodyBuilder = [];
res.addListener('data', function(chunk) {
    bodyBuilder.push(chunk);
});

When you're done, join with

var body = bodyBuilder.join('');

The reason for this is that strings are usually stored as contiguous arrays of characters. When extra characters are appended, the array may have to be moved in memory if there's not enough free space past the end of the string to store the extra stuff. An implementation may reserve some extra space, but how much is out of your control.

Upvotes: 2

Related Questions