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.

up vote 28 down vote accepted

2 main reasons:

  1. Contracts currently cannot read a string that's returned by another contract.
  2. 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.)
  • 3
    Would 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 9:40
  • 2
    Sounds correct to me, and the unpredictable gas usage is another good consideration. – eth May 10 '16 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.

  • why does the getByte11 cost more gas than getByte32? – Saad Malik Mar 20 at 3:39
  • 1
    @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 at 5:59

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.