Using a loop in inline assembly compared to a regular solidity for loop saves around 20% in gas cost.

I'm struggling however with looping over an array through inline assembly. Is this possible and if so, how?

Many thanks.

pragma solidity ^0.4.21;

contract Loop {
    uint[] array = [1, 2, 3, 4, 5];

    function returnNthElement(uint _index) returns (uint) {
        assembly {
            let index := _index
            let length := mload(sload(array_slot))
               { let i := 0 }
               lt(i, length)
               { i := add(i, 1)}
               //How to return element at index '_index' ? 

1 Answer 1


First, I don't think you need a loop. You can access the location of whatever element by its index in constant time.

As explained in this article, the location of an array's element is calculable the following way : you hash the slot of the array (here, it's 0), and this will give you the "starting location" of the array. You just have to add to it the index to shift to the appropriate location.

You will not that it's not the case all the time, it depends on what type of elements your array contains, because you will have to adapt your shifting (EVM works by 256 bits).

As for the code itself, with the informations you have been given, it should be simple.

  • 1
    The real life case is a dynamic array of struct types and the index is unknown , therefore the loop is needed.
    – Nico
    Apr 22, 2018 at 22:20
  • Then why do you pass the index? If the index is unknown and you need to find by checking the value of one of the struct's member, it will probably simplier to use a solidity loop Apr 22, 2018 at 22:30
  • 1
    Because it's an example? I know how to do it in solidity, i want to know how to do it in inline assembly to save about 15% gas cost on state changing functions using loops.
    – Nico
    Apr 28, 2018 at 16:29

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.