Structs in solidity are implemented as a hash map. They key of a map is hashed with keccak and the storage slot. A costly part of accessing a map is hashing the key to find the slot. When storing a struct in a mapping as opposed to multiple mappings of primitive types you can save the cost of multiple hashes. However when frequently only reading part of the struct, returning an entire struct to a call leads to overhad in memory usage. Below are a few test cases illustrating the different options and their gas usage.
As expected, the most simple, test_map()
uses the least amount of gas. The worst option
is if you have an external call that returns the entire struct even though only one element
is needed (test_structmap_no_getter
). Therefore if you have external methods access only partial data
from a struct always create a getter for it.