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?
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
and
If the record has not been initialized for some reason, the default value of the type is returned instead.