Contract Design – Event Logs vs Storage in Solidity: Optimization and Gas Price Considerations

contract-designeventsgas-priceoptimizationstorage

In my ethereum smart contract, I have a function that registers a user (by adding a user object to a mapping). I am also triggering an event after successful registration to notify the user about the same. I want to get the total number of users (which will be displayed on the website).

I know that event logs in ethereum are much cheaper than storage. So I am confused between the two choices:

  1. Take a variable in storage, initialize it from 0 and increment it every time a new user is registered. So variable will store the total number of users and can be easily accessed from the website frontend.

  2. Since I am triggering an event every time a new user is registered. So can I use the count of events triggered (as it will be equal to the number of users registered)? Do I need to fetch all the logs just to get the count? What if the number of users(or logs) is very large (10^6)?

Which option will be optimal (minimal gas price with fast response).

I am open to suggestions, If you know some other solution please let me know about it.

Best Answer

If you choose to use a counter in storage then it will increase the gas costs of registering a user but it will also allow you to access the count of users from other smart contracts. It's up to you to make that tradeoff. As an alternative if you don't have a counter in storage then you can have an event. Gas costs will be lowered for user registration. If you take this approach I suggest you run a background task that subscribes to events from your contract. This background task will listen to new events and increment a value in some centralized database. The website frontend can read this value from your database and show it.

Related Topic