0

My question is: Should I use uint40 for time in Solidity?

All the examples I've seen use uint256 for time, however, I think it's too wasteful -- while using uint32 is maybe a little aggressive due to its 86-year-till-overflow, the 34K-year-till-overflow from uint40 seems pretty safe to me.

Could there be any potential downfall from using uint40 that I'm not aware of?

Edit:

Sorry for not making myself clear enough earlier. Consider the following struct --

struct User {
    address user;   // 20 bytes
    uint40 userRegisterTime;    // 5 bytes
    uint40 userDepositTime;     // 5 bytes
    uint256 userBalanceWei;     // 32 bytes
}

Had the two time vars been defined as uint256, the struct would need 4 * 32-byte, while in the case of uint40, the first three vars can be packed into one 32-byte, saving 2 * 32-byte (reference, which I have verified -- https://medium.com/@novablitz/storing-structs-is-costing-you-gas-774da988895e )

Everybody agrees?

  • Better wasteful than being at risk of getting an overflow in one of your calculations, as a result of the compiler choosing the shortest type which is sufficient for the operation. For example, time * 2 will be stored into uint40, while the result might be larger than 40 bits. For this purpose only, it is already better to just keep all your stuff in uint256s. As to gas cost, keeping all your data aligned to 256 bits, will actually yield lower gas-cost. – goodvibration Jun 2 at 9:54
0

Solidity's VM is 256 bit, so uint40 will be padded to 256 bits and take more gas

Why does uint8 cost more gas than uint256?

  • For function variables, yes; For storage variables, smaller types could be more gas efficient -- I've added a sample case to my question -- sorry for missing it out earlier. – Jerry Ji Jun 2 at 11:18
  • For this exact case - yes. Storing the data will take less space, but it depends on your calculations inside the contract if it will take less or more gas overall, so it's a balance choice on your own. – KNK Jun 2 at 14:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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