Solidity Assembly – How to Extend Storage Array Length in Assembly?

arraysassemblysolidity

Is it possible to just "extend" an array length directly in Assembly?

Ideally that would fill the new values with equivalent "0" values.

Example:

  address[] internal owners;
  
  function mint(to, amount) {
    owners.push(to);

    assembly {
      // owners.length += amount - 1... :-S
    }
  }

I am trying to avoid/optimize this:

  function mint(to, amount) {
    owners.push(to);

    for (uint256 i; i < amount - 1; i++) {
      owners.push(address(0));
    }
  }

Best Answer

Is it possible to just "extend" an array length directly in Assembly?

Yes, you need to increment the length of the array which is located at the array's storage slot:

  function mint(to, amount) {
    owners.push(to);

    assembly {
     sstore(owners.slot, add(sload(owners.slot), sub(amount, 1)))
    }
  }

As per the documentation: https://docs.soliditylang.org/en/develop/internals/layout_in_storage.html#mappings-and-dynamic-arrays

Assume the storage location of the mapping or array ends up being a slot p after applying the storage layout rules. For dynamic arrays, this slot stores the number of elements in the array (byte arrays and strings are an exception, see below).

The value of the items in the array are then by default already set to 0x0000...000 etc.