So I was implementing a trading contract and need to keep a list of products on sale. I was using arrays but later switched to mappings.
So arrays implementation:
uint[] public productsOnSale;
uint public totalProductsOnSale;
// array of product to its position
mapping(uint => uint) productToIndex;
while sale can be achieved using
uint public totalProductsOnSale;
mapping(uint => uint) indextoProduct;
mapping(uint => uint) productToIndex;
Since in case of arrays we keep track of values at any index, we can achieve that using mapping as well.
Are there any downsides of using mappings instead of an array? In terms of computation time or in terms of cost (gas)?
productsOnSale.length;- you take length of your array.productsOnSale.push(value);- you add new element at the end of the array. In mapping if you will use existing key, you will overwrite it. – Tcс Sep 26 '18 at 18:04