0

I have a Solidity smart contract to run on the Ethereum network, that has a public mapping which stores a struct with several attributes. I must loop through all of those stored structs looking for a specific attribute value that may or may not be unique, (i.e. users['Joe'].age == "30"). Those might add to over 1000 structs, each having about 6 attributes.

What should I do, in terms of cost versus performance? Run an internal loop inside the contract and get only the results I want, or make a loop to call all of the structs individually, then run a loop outside of the blockchain to find them?

I'm kind of lost, here. Thank you.

f.poletto
  • 33
  • 1
  • 6
  • Please edit your question and show the current code, as well as reason for the looping. It's going to be much easier to understand with the code. – Petr Hejda Jun 08 '21 at 13:13

1 Answers1

0

Since I can't comment yet, I suppose all I can do is answer...

With the limited info on your situation, I suppose I would first make sure your decision to use a mapping is the best approach. I'd assume you've made sure it's a better solution for your storage structure than an array.

Looping through items in a smart contract is a quick way to burn up gas, and may quickly run you into the block gas limit. This basically makes it an extremely high cost just to run a check of something, even if you don't find what you're looking for.

From just the information given, maybe storing this data off-chain would be the best solution - picking only critical data to store on-chain. If it's crucial to have it all stored on-chain, I believe you're right to run your loops off-chain.

I'm very new, so trust any of these other guys before me. Just wanted to throw in my 2 Wei.

bcral
  • 31
  • 1
  • 4
  • Thank you for that information. That's exactly the kind of insight I was looking for. This test project of mine is a lottery on the blockchain. So I guess runnig all this system on the blockchain is off the table. Maybe I'll keep only the pseudo random for drawing the result, for transparency sake + get all the tickets and do all the processing off chain. Thank you for your opinion. – f.poletto Jun 08 '21 at 23:26