I know that generally it cost 5,000 gas to initialize memory variable. But simple smartcontract shows me that I misunderstand something.

pragma solidity ^0.4.24;

contract MemConsumption {
    uint256 a;
    uint256 b;
    uint256 c;
    uint256 d;

    struct My {
        uint256 a;
        uint256 b;
        uint256 c;
        uint256 d;

    function set(uint256 _a, uint256 _b, uint256 _c, uint256 _d) public {
        a = _a;
        b = _b;
        c = _c;
        d = _d;

    function test() public view returns (uint256) {
        return calc(My(a,b,c,d));

    function calc(My my) private pure returns (uint256) {
        My memory m = My(my.a, my.b, my.c, my.d);

        return m.a + m.b + m.c + m.d;

Function set expectedly cost ~100k gas - allocates 4 32-bytes words in storage.

But call of test confused me. I supposed it will cost me:

  • transaction call cost (~20,000);
  • gas for memory allocation of parameter My instance (it is passed by value as memory one) i.e. 5,000 * 4 = 2,0000;
  • gas cost of memory instantiation of memory m variable;

But in Remix I see that transaction cost is 22745. Why?

  • 1
    Well, you're doing a few arithmetic operations inside the calc function, aren't you (3 additions, to be accurate)? Those are not "for free" you know... – goodvibration Oct 4 '18 at 13:09
  • @goodvibration so what? It is unrelated to my question. – Alex G.P. Oct 4 '18 at 13:49

There's a difference between memory and storage. Storage (the first, more expensive example you give) is persistent storage that lasts between function calls. It costs, like you mention, 20k to initialize a slot in storage.

Memory (your second example), on the otherhand, is much cheaper. It's non-persistent, so you lose it from transaction to transaction. Think of it like local variables in functions, because that's what it's designed to be used for. Exact costs can be seen on page 25 of the yellow paper.

  • return calc(My(a,b,c,d)); allocates new memory variable (otherwise I cannot imagine how is it allocated to pass it to next function. This variable consumes 4 32bytes words (as I described), so it should consumes at least 20k more gas. It doesn't. – Alex G.P. Oct 7 '18 at 17:22
  • Do you mean that something you called "local variable" isn't memory one? – Alex G.P. Oct 7 '18 at 17:23
  • Yes, it allocates a new memory variable. But as my answer explains, memory variables and storage variables are vastly different in price. storage is orders of magnitude more expensive than memory. – flygoing Oct 7 '18 at 19:16
  • You're right. I don't know why I messed with gas cost, 5k I'll pay for changing storage vars. Thanks! – Alex G.P. Oct 9 '18 at 4:36

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.