Hi @B_S,
Leaving aside the similarities and differences of how mappings and arrays are compiled into bytecode and stored by the EVM ā which, due to the peculiarities of the EVM, isnāt the same as how arrays and maps in other programming languages are saved in computer memory ā letās consider the similarities and differences that determine how, on a more practical level, arrays and mappings are used by Solidity developers to write their smart contract codeā¦
The values stored in an array are ordered according to a fixed sequence of indices (0,1, 2, 3 etc.). Each index number and its associated value is a key/value pair (each unique key being an index number). This means that, as well as being able to reference or retrieve values by their specific index number (if we know it), arrays can also be iterated over. The ability to iterate over an array, means we can search for specifc data stored within it, without needing to know specific index numbers (keys). In Solidity, only fixed-size arrays can have values added to specifc index numbers. To add values to a dynamic-sized array, they have to be pushed using the .push()
array method.
Mappings are also data structures which store key/value pairs. However, unlike arrays, values can be mapped to unique keys of data-types other than uint
e.g. addresses or strings. There is, therefore, no need for values to be added and stored in a mapping according to a fixed, sequential order of integers, which must begin with 0.
Because a mapping can be defined with uint
keys, values could potentially be added and mapped according to a fixed sequence of uint
keys which mirror an arrayās index values. However, this would most probably be an inefficient use of a mapping, and it is generally accepted that mappings cannot be iterated over (although, strictly speaking, this doesnāt seem to me to be completely true). In Solidity, mappings are commonly used to map values to Ethereum addresses, and in this case, they cannot be iterated over. In order to add, modify, reference or retrieve a value mapped to an address, this unique address needs to be known. This gives mappings the ability to provide more in-built data privacy than arrays.
Generally speaking, if you need to store and look up large amounts of data, using mappings will save you a noticeable amount of gas (as opposed to using arrays); and, as you say, usually ā¦
With large amounts of data, using arrays, where mappings could provide the same results, runs the risk of transactions running out of gas and failing, because the gas limit has been reached.
I hope this gives you a clearer picture of the differences between mappings and arrays in Solidity. Let me know if you have any further questions.