In many Solidity examples I read that use strings for parameters or return values, I see they are typed as bytes32
although there's a string
type. What is the real reason for that?
Thanks.
2 Answers
2 main reasons:
- Contracts currently cannot read a
string
that's returned by another contract. - The EVM has a word-size of 32 bytes, so it is "optimized" for dealing with data in chunks of 32 bytes. (Compilers, such as Solidity, have to do more work and generate more bytecode when data isn't in chunks of 32 bytes, which effectively leads to higher gas cost.)
-
5Would this mean that if using string instead of byte32 this would make the contract split the string in 32 bytes chunk and then have an unpredictable number of chunks and thus have an unpredictable gas usage on this part of the code? May 10, 2016 at 9:40
-
3Sounds correct to me, and the unpredictable gas usage is another good consideration.– eth ♦May 10, 2016 at 9:46
I have test in this site https://ethfiddle.com/zLxE5Y-8B4
contract TestGas {
string constant statictext = "Hello World";
bytes11 constant byteText11 = "Hello World";
bytes32 constant byteText32 = "Hello World";
function getString() payable public returns(string){
return statictext;
}
function getByte11() payable public returns(bytes11){
return byteText11;
}
function getByte32() payable public returns(bytes32){
return byteText32;
}
}
And function getString
spent 21875 gas,
function getByte11
spent 21509 gas,
function getByte32
spent 21487 gas.
So if your string length is fixed, just use bytes32.
-
3
-
6@SaadMalik The EVM works with 32 bytes words. When your data is smaller than 32 bytes, every operation related to this data will downscale from 256 bits to 8 bits(32 bytes = 256 bits), so EVM need much more gas. Mar 21, 2018 at 5:59