Solidity – Why uint8 Costs More Gas than uint256

gassolidity

contract A {
  uint8 a = 0;
}

costs 20150 + 2000 gas during creation.

as compared to

contract A {
  uint a = 0;   // or uint256
}

costing 5050 + 2000 gas during creation

It is odd that a variable that's taking less storage space is costing more gas. Why is that so?

Best Answer

The EVM works with 256bit/32byte words (debatable design decision). Every operation is based on these base units. If your data is smaller, further operations are needed to downscale from 256 bits to 8 bits, hence why you see increased costs.

Btw, if you toggle the "Details" on the online solidity compiler, it will give you the exact assembly dump where the extra opcodes are from. I didn't have time now to interpret them, but if you do and find there's something extra, I'm sure the Solidity team would be happy to add optimizations to work around them.

Related Topic