I am learning solidity/ethereum and I came across this situation:
I have a mapping(address => unit) that keeps track of how much every address is paying my contract, and at some point, I have to compute how much % of the total pool has one user contributed with. (for example, if the total pool is 100 ethers and user contributed 10 ethers, he has contributed with 10% of the total pool).
In order to do so, I need to have access to the total pool. My first instinct was to have a variable totalPool which will keep track of the total value, therefore every time an address is paying the contract, totalPool += msg.value; However, while learning about the EVM, I kept reading how expensive it is to operate on the storage.
My question is, what is cheaper in terms of gas, to keep track of the total pool and operate on memory every time an address pays the contract, or to compute the total pool every time when I need to find out the ratio contribution?
From what I understand of your use case, your first instinct is probably the simplest and the best solution unless you have an easy way to compute the total pool. You have to keep in mind that in solidity, it is impossible to loop over the elements of a mapping to sum them up. So unless it is possible to calculate the size of your pool using other variables that would be stored anyway, the total pool variable is most likely the best way to keep track of the pool size.
I highly recommend that you test as many implementations as you can come up with. Both the ethers.js and web3.js libraries have functions that allows you to test how much gas should be required to execute a transaction.