How do you optimize gas in Cairo with Uint256/felt?

132 views Asked by At

I’m learning Cairo and I want to know more about Gas Optimization. In Solidity compiler, there is a difference between writing uint128 and uint256. Similarly to C and other languages, for example:

contract ThisIsNotAnOptimizedContract{
    uint128 Zero;
    uint256 One;
    uint128 Two;
}

contract ThisIsAGasOptimizedContract{
    uint128 Zero;
    uint128 Two;
    uint256 One;
}

uint128 variables each occupy a separate uint256just for themselves, wasting 128 bits for each slot (Like the first contract). The Solidity compiler puts 2 uint128 in the one 256-bit memory slot when they are declared next to each other.

I’m curious if there is any similar issue in Cairo. Uint256 uses two felt objects for low/high bits of the value.

struct Uint256 {
    // The low 128 bits of the value.
    low: felt,
    // The high 128 bits of the value.
    high: felt,
}

Is there any similar practice in Cairo to optimize felt and Uint256 objects to save some compiler steps?

2

There are 2 answers

0
David Barreto On

AFAIK, there isn't a similar optimization technique in Cairo as what you described for Solidity. It might help to keep in mind that a felt is stored using 251 bits so anything bigger than that like uint256 will need more than one felt to represent it.

0
amanusk On

Solidity and the EVM use slots to order contracts storage. Slots are allocated in the order the variables are defined. Also, the EVM uses a 256 bit word, and hence the unoptimized way to define the variables you described. (This allocation method is also the reason storage can be overridden or "forgotten" when upgrading contracts using a proxy pattern. This was the reason for various smart contract hacks)

In StarkNet, storage slots are allocated by using the hash of the variable name. So regardless of the order, you define your variables, they will be allocated the same storage slot. (This also mostly solves the storage override issue described above).

You can read more on StarkNet storage allocation in the docs:

https://docs.starknet.io/documentation/architecture_and_concepts/Contracts/contract-storage/