The OpenZeppelin ERC-721 library has a function called balanceOf(address owner), which enables one to know how many tokens an address owns. Furthermore, one can also use a mapping in order to keep track of how many tokens an address owns, such as mapping(address => uint) ownerCount.

What are the advantages of using one over the other (in terms of gas cost and performance for instance), and when should one be used instead of the other?

Thank you. J


There is no advantage in terms of gas, let alone the fact that you don't even need gas in order to call a read-only function, since no mining is required (but for the sake of this question, let's assume that you call it from an actual state-changing function, which does consume gas).

The additional cost of calling a function instead of reading the variable directly is negligible.

But you could still claim that in terms of gas, using a function is actually a disadvantage.

However, there is a notable advantage in the aspect of coding-maintenance:

Instead of declaring the mapping as public and allowing you to call it as a function, they declare it as private and implement a function which returns the same, thus preventing anyone who inherits their contract from making the mistake of modifying that mapping themselves.

  • Thank you GoodVibration!
    – JF0001
    Nov 24 '20 at 21:25

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.