7

Since both uint256 and bytes32 space are 2^256, what are the general practices for prioritizing using one over the other? why is bytes32 more expensive to execute gaswise than uint256?

1 Answer 1

7

uint256 is generally used for:

  • Addresses
  • Numbers
  • Account balances
  • Doing math like + - * / or **

bytes32 is generally used for:

  • Small strings of no more than 32 characters
  • Hashes (the sha3(..) functions returns a bytes32)
  • Raw data (of whatever meaning you like)
  • Situations where you need to read a specific byte like a[4]

The comparison operators work for both uint256 and bytes32:

<= < >= > == !=

Also, the bitwise operators work for both uint256 and bytes32:

& | ^ ~ << >>

2
  • 1
    Thanks Jesse, can you explain why bytes32 is more expensive than uint256 of same size?
    – 6egic
    Commented Oct 12, 2017 at 17:53
  • 1
    @ABGhostCoder I do not know. I'm trying to analyze the bytecode produced by the Solidity compiler. It seems that the compiler uses 3 extra instructions to load a bytes32 function parameter, compared to a uint256. Also, it uses 11 extra instructions to return a bytes32. With optimizations turned on, these differences disappear completely. I would assume that as the optimizer is improved more and more, bytes32 should eventually be equally expensive as uint256.
    – Jesbus
    Commented Oct 12, 2017 at 18:26

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.