0

One of my library functions calls another internal pure function like this:

library MyLibrary {
  function foo(uint256 x) internal pure returns (uint256 result) {
      // do important work
  }

  function bar(uint256 x) public pure returns (uint256 result) {
      // ...
      uint256 foo_value = foo(x);
  }
}

But foo has a small body, so I thought what if I avoided calling it? Would I save gas?

library MyLibrary {
  function foo(uint256 x) internal pure returns (uint256 result) {
      // do important work
  }

  function bar(uint256 x) public pure returns (uint256 result) {
      // ...
      uint256 foo_value;
      // do important work here instead of in "foo"
  }
}

But no, I wouldn't save gas. Both implementations cost the same. Why is that?

2
  • Did you try with optimization enabled?
    – Ismael
    Mar 27 at 17:15
  • 1
    Yes, with both optimisation enabled and disabled. Mar 27 at 17:29
1

Possibly someone with deeper knowledge of compilation details will chime in with more precision.

Intuitively, one might expect a slight difference to account for the extra steps of jumping into another section of code, packing return arguments, and unpacking received arguments, and them carrying to assign the value to foo_value. The difference could be negligible.

In practice, I suspect the compiler is "unrolling" the pure function so it compiles as though it's actually written "in-line". That is what you are proposing at the source code level in the second example and it is possible that the compiler does it for you. If that's the case, one would expect no difference or almost no difference.

If you care to drill in to study it, you might use a debugger like Remix's built-in tools to step over the code and observe the bytecode as it happens. They might be exactly the same or they might have minor differences with similar cost. I guess the big factor to focus on is whether the first example has extra JUMP opcodes to jump in and return back, or if it carries on in a linear fashion without extra "help" from you.

In practice, it's often a "deep enough" understanding of the compiler to know where important difference might be and experimentally working out which way is better. Indeed, results are sometimes surprising.

Hope it helps.

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.