1

Let's say I have an array in storage:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;

contract Test  {
    uint256[] s_array = [1,2,3,4,5,6,7,7,8,8,8,8,8,8,8,8,8,8,8];

    function doStuff() public{
        uint256[] memory array = s_array;
    }
}

In my doStuff function, are we calling SLOAD multiple times to put each element into the array in memory? Or just once?

1 Answer 1

2

Yes, every element in an array is loaded with the sload opcode.

An example of loading element at position 0 from an array from the huff low-level language:

#define constant ARRAY_STARTING_SLOT = FREE_STORAGE_POINTER()

/* Macros */
#define macro READ_ELEMENT_ZERO_FROM_ARRAY() = takes (0) returns (0) {
    0x04 calldataload          // [array index to read from] array index should be 0
    iszero                        // [index == 0]
    success jumpi                 // [iszero_result]    

    0x00 0x00 revert

    success:
        [ARRAY_STARTING_SLOT]      // [ARRAY_STARTING_SLOT, iszero_result]
        0x00 mstore                // [iszero_result] // Memory now has the starting slot 
        0x20 0x00                  // [offset, size, iszero_result]
        sha3                       // [HashedStorageSlot, iszero_result] // sha3 reads from memory based on the offset & size given
        sload                      // [value_in_array, iszero_result]

        0x00 mstore                // [iszero_result] // Memory now has the starting slot
        0x20 0x00 return
} 

Every element you load into memory has to be pulled from an sload.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.