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);
}
}
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.