# Memory consumption confusing case

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?

• 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... Oct 4, 2018 at 13:09
• @goodvibration so what? It is unrelated to my question. Oct 4, 2018 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.
• 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. Oct 7, 2018 at 17:22
• Do you mean that something you called "local variable" isn't memory one? Oct 7, 2018 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. Oct 7, 2018 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! Oct 9, 2018 at 4:36