In solidity if you need to add an item to a mapping, i believe thats then called adding it to storage, from a function, is it better to make a memory variable of the struct and then pass that to the mapping. Or can you just better directly pass the struct to the mapping? it saves me an extremely little amount of gas to just write directly to add the struct directly to the mapping.

Here is an example of what i mean:

Counters.Counter private _ids;

Struct x = {
  uint256 id;
  uint256 value;

mapping(uint256 => x) private _xs;

function xCreate(uint256 _price) external {

  uint256 itemId = _ids.current();

  //Do it this way(1) ->
  X memory x = X(
  _xs[itemId] = x;
  //Or do it this way(2) ->
  _xs[itemId] = X(

For me the second way seems way more logical. But i have seen multiple examples of people using the first way. So is there a reason to not do it like the second example? I just want to make sure im not missing an important concept.

  • Both should work, I don't think one is better than the other. Perhaps 2/ is cheaper but you will have to test the gas consumption.
    – Ismael
    Feb 2, 2022 at 3:31
  • 2
    thanks for responding, number 2 is indeed cheaper by a very miniscule amount.
    – Zercon
    Feb 2, 2022 at 6:28

1 Answer 1


It should work on primitive types and the second approach is far better... but check this example where it will fail for both cases above:

struct Swap {
    address owner;
    address allowed;
    uint256 expiry;
    Asset[] biding;
    Asset[] asking;

This struct has arrays inside and we cannot call it like this:

swaps[swapId] = Swap(owner, allowed, expiry, biding, asking);

This will revert with:

Copying of type struct ISwap.Asset memory[] memory to storage not yet supported

And you cannot even set a storage like:

Swap storage swap

Because the Asset[] type is another struct, an array of structs inside a struct. It will become memory and then not assignable to storage pointers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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