messagepack icon indicating copy to clipboard operation
messagepack copied to clipboard

Isn't it better to use switch instead of if-elseif ?

Open jodinathan opened this issue 3 years ago • 0 comments

Take the unpackInt as example:

    if (b <= 0x7f || b >= 0xe0) {
      /// Int value in fixnum range [-32..127] encoded in header 1 byte
      v = _d.getInt8(_offset);
      _offset += 1;
    } else if (b == 0xcc) {
      v = _d.getUint8(++_offset);
      _offset += 1;
    } else if (...) {
    } else {
      throw _formatException('integer', b);
    }

isn't it better if we change it to use switch instead of those ifs? ie:

    if (b <= 0x7f || b >= 0xe0) {
      /// Int value in fixnum range [-32..127] encoded in header 1 byte
      v = _d.getInt8(_offset);
      _offset += 1;
    } else {
      switch (b) {
        case b == 0xcc:
          v = _d.getUint8(++_offset);
          _offset += 1;
       break;
      default: 
        throw _formatException('integer', b);
    }

I am not sure, but maybe the compiler uses a goto with the switch but not with the if-elseif because of the first if block (b <= 0x7f || b >= 0xe0).

jodinathan avatar Jul 29 '21 14:07 jodinathan