Arrays vs. Mappings

Learn the differences and similarities between arrays and mappings in Solidity.

Arrays and mappings are two ways of storing complex data in Solidity. Each comes with advantages and disadvantages.

Differences between arrays and mappings

We can loop through arrays using for and access an element in an array using the zero-based index of the element. We can’t do these things with mappings. As we’ve learned, arrays in Solidity have push member functions to add, but unlike in JavaScript, there are no filter or find functions. This means that to access a specific element or item in an array in Solidity, we must know its position or index in the array.

One way to look up an element is to loop through the array and compare the current iterations. This can quickly become an issue for large arrays or those where we have many operations going on and can’t adequately track them. Because of this, it’s much safer, faster, and more cost-effective—looping through arrays costs a lot!—to use mappings to store complex data. We can easily look up the desired element using the key we stored it with in a single statement.

Rewriting our contract

Let’s rewrite our contract to store contacts as mappings, not arrays. You can test this out in the Remix IDE widget at the end of the lesson.

Get hands-on with 1200+ tech skills courses.