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.
Asked
Active
Viewed 1.4k times
39
eth
- 85,679
- 53
- 285
- 406
Nicolas Massart
- 6,783
- 2
- 29
- 63
2 Answers
39
2 main reasons:
- Contracts currently cannot read a
stringthat'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? – Nicolas Massart May 10 '16 at 09:40
-
3Sounds correct to me, and the unpredictable gas usage is another good consideration. – eth May 10 '16 at 09:46
9
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.
Xat_MassacrE
- 121
- 1
- 3
-
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. – Xat_MassacrE Mar 21 '18 at 05:59