My use-case requires that I feed my contract with a long string (Base64 data), which requires to split it and send it over several transactions so as to not reach gas limit. Then the contract rebuilds the Base64 data by concatenating the string received, like so:

pragma solidity 0.6.8;

contract Concatenation {

    string public base64Data;

    function concat(string memory pieceOfData) external returns (string memory) {
        base64Data = string(abi.encodePacked(base64Data, pieceOfData));
        return base64Data;


This snippet is highly inefficient as base64Data is basically overwritten at each iteration, instead of simply being appended each pieceOfData. This creates an exponential gas cost as the written data gets larger and larger (as far as i understand the EVM).

Is there a more gas-efficient solution than the snippet above to concatenate a string?

NB: This data has to be stored in the smart contract state (cannot use Swarm/IPFS)

  • have you tries hashing it client side and storing the hash in the contract? That way you move most of the computation client side
    – 0xsegfault
    Commented Jun 1, 2020 at 10:58
  • mmh i m not familiar at all with string hashing, let me look into it first. If it stringly reduces computation it could be a good fallback solution, if it turns out there is no efficient method to concatenate strings in Solidity Commented Jun 1, 2020 at 12:20
  • 1
    @PmRivière Do you need to string to be concatenated? does it work storing them in an array of strings? You can concatenate them in a getter function. The other option will be to use assembly to direclty modify contract's storage.
    – Ismael
    Commented Jun 1, 2020 at 15:37
  • @Ismael I think that could work! Didn't think of the problem that way. I'll try and update here. I'm not familiar with assembly but will look into it as well. Thanks! I'm still surprised there's no better way to concatenate strings, I can't upload more than 80kb of data in chunks before touching the out-of-gas (in a Truffle env) Commented Jun 1, 2020 at 19:23
  • @PmRivière Ethereum is pretty bad for storing large amounts of data. A common approach is to store a fingerprint of the data and store it off-chain in IPFS or something similar. If you need to manipulate data perhaps something like truebit protocol.
    – Ismael
    Commented Jun 1, 2020 at 21:36


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.