Skip to content

Instantly share code, notes, and snippets.

@themasch
Created December 19, 2013 12:31
Show Gist options
  • Save themasch/8038446 to your computer and use it in GitHub Desktop.
Save themasch/8038446 to your computer and use it in GitHub Desktop.
faster for me (v0.10.21)
function faster_concat(list)
{
var len = 0;
var listLen = list.length;
var offset = 0;
if(listLen === 1) {
return list[0]
}
for(var i=0;i<listLen;i++) {
len += list[i].length
}
var buf = new Buffer(len)
for(i=0;i<listLen;i++) {
var src = list[i]
src.copy(buf, offset)
offset += src.length
}
return buf
}
@jhermsmeier
Copy link

I've made the experience that references are faster in small loops,
and the += op is not optimized in some older versions of V8, I think;
So maybe something like this:

function concat( list ) {

  if( list.length === 0 )
    return new Buffer( 0 )

  if( list.length === 1 )
    return list[0]

  var i, bytes = 0

  for( i = 0; i < list.length; i++ ) {
    bytes = list[i].length + bytes
  }

  var buffer = new Buffer( bytes )
  var offset = 0

  for( i = 0; i < list.length; i++ ) {
    list[i].copy( buffer, offset )
    offset = list[i].length + offset
  }

  return buffer

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment