1

I am currently in the process of creating a smart contract on T-Sol that will require periodic additions of new elements to a mapping. If these elements are not already present in the mapping, they will be initialized accordingly.

struct Person {
  uint age;
  string name;
}

mapping(uint16 => Person) testMapping;

I'm wondering which way will be more efficient in terms of gas consumption?

  • Option 1
testMapping.getAdd(i, Person(0, ""));
  • Option 2
if (!testMapping.exists(i)) {
  testMapping[18] = Person(0, "");
}

Is there a better way of initialization?

cryonyx
  • 13
  • 2

1 Answers1

1

First of all, there's no such thing as 'T-Sol'; the language is Solidity, all the syntax rules apply.

In Solidity, both local and state variables are initialized with default values. Thus, elements of your mapping are {0, ""} by default; you don't need to write any additional code.

Most of the time, the optimal pattern of working with mappings is as simple as

testMapping[i] = Person(anAge, aName);

and

uint thatAge = testMapping[i].age;

If the record has not been initialized for some reason, the default value of the type is returned instead.

ilyar
  • 1,331
  • 12
  • 21
Boris
  • 36
  • 2
  • Unfortunately, it doesn't answer my question about which method is more efficient by gas consumption. – cryonyx Aug 09 '23 at 08:36