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
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 abytes32
) - 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
:
&
|
^
~
<<
>>
-
1Thanks Jesse, can you explain why bytes32 is more expensive than uint256 of same size?– 6egicCommented 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 auint256
. Also, it uses 11 extra instructions to return abytes32
. 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 asuint256
.– JesbusCommented Oct 12, 2017 at 18:26