cryonyx
cryonyx

Reputation: 13

Which way of initializing a mapping item consumes less gas in T-Sol?

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?

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

Is there a better way of initialization?

Upvotes: 1

Views: 47

Answers (1)

Boris
Boris

Reputation: 36

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.

Upvotes: 1

Related Questions