Use string type or bytes32?

  • What are the benefits to using string datatypes over bytes32 to represent text data. It seems my contract runs into an out of gas exception when I switch the data structures from bytes32 to string.

  • eth

    eth Correct answer

    4 years ago

    Why string instead of bytes32?

    Use string for arbitrary-length string (UTF-8) data that's longer than 32 bytes. Frontends can decode a long string easier using methods like web3.toAscii or UTF-8 (when issues are fixed), instead of implementing the logic of UTF-8 decoding a series of bytes32.

    From Solidity docs:

    As a rule of thumb, use bytes for arbitrary-length raw byte data and string for arbitrary-length string (UTF-8) data. If you can limit the length to a certain number of bytes, always use one of bytes1 to bytes32 because they are much cheaper.

    String literals may also be helpful or convenient:

    String literals are written with either double or single-quotes ("foo" or 'bar')...

    String literals support escape characters, such as \n, \xNN and \uNNNN. \xNN takes a hex value and inserts the appropriate byte, while \uNNNN takes a Unicode codepoint and inserts an UTF-8 sequence.

    Why bytes32 instead of string?

    Answered in Why do Solidity examples use bytes32 type instead of string?

    bytes32 uses less gas because it fits in a single word of the EVM, and string is a dynamically sized-type which has current limitations in Solidity (such as can't be returned from a function to a contract).

    I am not sure if I understood the last sentence - string return types work in current Solidity compiler.

    @MikkoOhtamaa Emphasis is *to a contract*: I don't think is supported yet.

    Ok so if you have a controlling contract and it's accessing data from another contract which is returning text that is longer than 32 bytes, you would need to return it in a bytes32 array?

    @ethereal Sounds right, give a size to the array like bytes32[3]. There may be assembly ways to get the size of the data being returned and avoiding a hardcoded size, for example the contracts in

    If a contract cannot access another contract's string variables, then what can? Can web3? What if I want to store a list or array of 60-character strings, but I will need to access them from another contract or program, how do I do it?

License under CC-BY-SA with attribution

Content dated before 7/24/2021 11:53 AM