Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

further optimize BytesParsing assembly and gas cost #44

Merged
merged 3 commits into from
Aug 23, 2024

Conversation

nonergodic
Copy link
Collaborator

@nonergodic nonergodic commented May 27, 2024

what it says on the tin:
instead of using the uint function version to read bytes and then have casts that also have to shift stuff around, it's more efficient to just read the bytes directly and have Solidity take care of cleaning up the dirty bytes when returning bytes<n>

More explicitly, when compiling e.g. this sample contract:

contract ByteCode {
  function foo() public payable returns (bytes16 ret) { unchecked {
    bytes memory buf = abi.encodePacked(
      bytes32(0x3300000000000000000000000000000000000000000000000000000000000044)
    );
    (ret, ) = BytesParsing.asBytes16Unchecked(buf, 3);
  }}
}

The original assembly is:

  /* \"src/BytesParsing.sol\":19598:19711  assembly (\"memory-safe\") {... */
0x13
add
mload
  /* \"src/ByteCode.sol\":95:394  contract ByteCode {... */
0x80
shl
not(0xffffffffffffffffffffffffffffffff)
and
dup2
mstore

While the new, optimized version gives:

  /* \"src/BytesParsing.sol\":20679:20803  assembly (\"memory-safe\") {... */
0x23
add
mload
not(0xffffffffffffffffffffffffffffffff)
  /* \"src/ByteCode.sol\":95:394  contract ByteCode {... */
and
dup2
mstore

@nonergodic nonergodic changed the title further optimize assembly and gas cost further optimize BytesParsing assembly and gas cost Aug 22, 2024
@nonergodic nonergodic merged commit 020d9f6 into main Aug 23, 2024
1 check passed
@nonergodic nonergodic deleted the improve-bytes-parsing-assembly branch August 23, 2024 04:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants