5

Suppose your contract has a very simple function, F(), which takes about 1,000 gas to process. Suppose you want to call that function 100 times. Since there is an overhead of about 21,000 gas per transaction, you'll be paying 2,200,000 gas. But, if your contract has a function:

function Fs(uint n){
    for (uint i=0; i<n; ++i)
        F();
}

You could perform the exact same operation with a single call, Fs(100), which would cost only 121,000 gas, a 94.5% reduction. Is there any way to send several calls to F in a single transaction, so you can achieve the same effect even when the contract didn't specifically optimize for it?

5

Under what circumstance are you calling F() repeatedly?

Name the place where you're calling from C(). There's multiple possibilities:

  1. C() and F() are in the same contract. In this situation, C() can call F() repeatedly without any major overhead.

  2. C() is in one contract, and F() is in another contract. In this situation, C() can repeatedly call F() within the same transaction, but it will cost some gas each time. (Less than sending a separate transaction every time, however)

  3. C() is outside of Ethereum entirely (i.e. a javascript function via web3) and F() is a constant function (that is, it does not modify the contract's state.) In this situation, C() can call F() as many times as it likes, for free. It will simulate transactions rather than actually sending them.

  4. C() is outside of Ethereum, and F() is non-constant. In this situation, each transaction will cost the full amount. It's possible you can write another contract to call F() repeatedly, as in 2.

Note that there is a significant difference between a transaction and a call. Users create transactions, which may contain any number of calls. A call, also called an internal transaction or a message call, is when one account or transaction interacts with another. Contracts can only perform the latter.

(This terminology is somewhat obscure, and you'll probably find people confusing the two--I've done so myself.)

  • 1
    For #1, there's a case when it will cost as #2 and that's if F has been marked with external visibility (even though C and F are in the same contract), as in function F() external ... – eth Dec 2 '16 at 9:06
  • You know, I don't think I've ever seen someone use the external modifier – Tjaden Hess Dec 4 '16 at 7:39

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.