Unnecessary storage assignments in MappingStorageLib
waste gas
In MappingStorageLib
, the store
function stores a memory representation of a Mapping
into storage. It stores the length of the mapping repeatedly into each of the storedEntries
.
function store(MappingStorage storage self, Mapping memory newValue) internal {
if (self.value.entries[0]._length > 0) revert MappingStorageInvalidError();
StoredMappingEntry[] memory storedEntries = new StoredMappingEntry[](Math.ceilDiv(newValue._ids.length, 7));
for (uint256 i; i < newValue._ids.length; i++) {
if (newValue._ids[i] > uint256(type(uint32).max)) revert MappingStorageInvalidError();
storedEntries[i / 7]._length = uint32(newValue._ids.length);
storedEntries[i / 7]._ids[i % 7] = uint32(newValue._ids[i]);
}
for (uint256 i; i < storedEntries.length; i++) {
self.value.entries[i] = storedEntries[i];
}
}
On the other hand, the read
function only reads storedEntries[0]._length
to find the length of the Mapping
. Instead of writing _length
many times and in a new location per seven values, it only needs to be written into one location. Consider refactoring so that _length
is a property of StoredMapping
instead of StoredMappingEntry
.