You've answered 0 of 46 questions correctly. (Clear)

Question #45 Difficulty: 3

According to the Solidity 0.8.17 compiler (200 optimization runs)

    // Which contract will use fewer storage slots to save the true/false value for an incremental set of key values, A, B, C, or SAME (for the same gas)?

contract A {
  mapping(uint256 => bool) values;

  function isSet(uint256 key) external view returns (bool) {
    return values[key];
  }

  function set(uint256 key, bool value) external {
    values[key] = value;
  }
}

contract B {
  mapping(uint256 => uint256) bits;

  function isSet(uint256 key) external view returns (bool) {
      uint256 _block = bits[key / 256];
      uint256 _mask = uint256(1) << uint256(key % 256);
      return _block & _mask != 0;
  }

  function set(uint256 key, bool value) external {
    if (value) {
      bits[key / 256] |= uint256(1) << uint256(key % 256);
    } else {
      bits[key / 256] &= uint256(0) << uint256(key % 256);
    }
  }
}

contract C {
  struct Packed {
    bool[32] value; // 1 packed storage slot
  }
  mapping(uint256 => Packed) internal packed;

  function isSet(uint256 key) external view returns (bool) {
      return packed[key / 32].value[key % 32];
  }

  function set(uint256 key, bool value) external {
    packed[key / 32].value[key % 32] = value;
  }
}

Answer:

Problems? View a hint or try another question.

I give up, show me the answer (make 3 more attempts first).

Mode : Training

You are currently in training mode, answering random questions. Why not Start a new quiz? Then you can boast about your score, and invite your friends.

Contribute

Create your own!