Difference between abi.encodePacked(string) and bytes(string)

Hi there, is there a difference between the two functions in the title? I did a little test, and found bytes(string) costs roughly 445 less Gas.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract Test {

    function getBytes(string memory str) public pure returns (bytes memory) {
        return abi.encodePacked(str);
    }

    function getBytes2(string memory str) public pure returns (bytes memory) {
        return bytes(str);
    }
    
}
3 Likes

The first is copying the memory, the second is just casting the pointer type.

4 Likes

@frangio Thanks. Apparently, casting a pointer type costs less than copying the memory.

what if the functions were this way:
The string wasn't a varible...

        bytes memory subString = abi.encodePacked("strrrrr");
        return subString;
    }

    function encodeBytes() public pure returns (bytes memory){
        bytes memory someStr = bytes("strrrrr");
        return someStr;
    } 

Hi, welcome to the community! :wave:

For these two different functions

function getBytes2(string memory str) public pure returns (bytes memory) {
    return bytes(str);
}
function getBytes2() public pure returns (bytes memory){
    bytes memory someStr = bytes("strrrrr");
    return someStr;
}

I think

  • In the first function, bytes(str) copies the input string str into memory and returns the resulting byte array. This copying operation consumes gas, particularly for longer strings.
  • In the second function, bytes("strrrrr") also creates a byte array in memory, the string is hardcoded, the compiler can optimize this process, so it will reduce gas consumption.