When should you use array or mapping in solidity?

Let's say I have multiple question questionnaire, with one question, and I want to store the responses of different people(address) in a smart contract. What is the best way to store them. In an array or a mapping?

For example:

struct Answer {
    address answerer; // address of the answerer.
    uint answer; // multiple choice answer.

mapping(address => uint) public answers;

Answer[] public answers;

When should I use either of the above?


It always depends on your needs.

The biggest difference is that you can't iterate over a mapping. So if you store two entries (key => value) in a mapping, there is no way to get the values without knowing the keys.

In your example, it also depends on your needs. If you only want to access the answers based on known key (so for example a function which takes an address as input and returns its answer), then you should use a mapping. But if you need to be able to find out how many answers have been given and/or from which addresses, you can't use mapping (at least alone).

Sometimes the optimal solution is to use both: store the actual data in mapping and then store the keys in a separate array, over which you can iterate. The reason is that accessing the actual values is much easier & cheaper from a mapping, given the key. If the values are only in an array, you have to iterate over the whole array to find the right entry.

Arrays also have the downside that if it grows too big, your contract may become unusable. If, for example, you need to search for a value from the array and iterating the whole array costs more than the block gas limit, the contract is basically bricked and useless.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.