JS 序列化类

最近在搞阿里云MQTT。发现消息解析的JS代码另人发指。主要是物模型序列化,太垃圾了。就自己写了一个更简单的Archive类。阿里的工程师都是傻逼吗?

class Archive {
  constructor(capacity) {
    this.capacity = capacity;
    this.size = 0;
    this.u8array = Array(this.capacity);
  }

  _check_resize(){
      if ( this.size < this.capacity) return ;      
      this.capacity = this.capacity*2;
      var newarray = Array(this.capacity);
      for (var i = 0; i < this.size; ++i) newarray[i] = this.u8array[i];
      this.u8array = newarray;
  }
    
  SaveUint8(data ){
      this._check_resize();
      this.u8array[this.size] = data;
      this.size+=1;
  }

  SaveUint16(data){
      this._check_resize();
      this.u8array[this.size] = (data&0xFF00)>>8;
      this.size+=1;

      this._check_resize();
      this.u8array[this.size] = (data&0x00FF);
      this.size+=1;
  }
  GetRawArray(){
      return this.u8array.slice(0,this.size);
  }
}

console.time("test1");
for (var i=0;i<1000;++i){
    var saver1 = new Archive(32);
    for (var j=0;j<100;++j) saver1.SaveUint16(0x1234);
    var result = saver1.GetRawArray();
}
console.timeEnd("test1");

console.time("test2");
for (var i=0;i<1000;++i){
    var payloadArray = [];
    for (var j=0;j<100;++j)  payloadArray = payloadArray.concat(buffer_int16(0x1234)); 
}
console.timeEnd("test2");

function buffer_int16(value) {
    var uint8Array = new Uint8Array(2);
    var dv = new DataView(uint8Array.buffer, 0);
    dv.setInt16(0, value);
    return [].slice.call(uint8Array);
}