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.