I am presenting my use case here. Let's think of a dating app where each candidate enters their preferences and we store their data and add them to an array. when someone enters that matches with any of the persons in order and they become partners we remove the person from the array. I have seen the implementations of this delete an array element efficiently, but if the array consists of 1000 entries and we want to remove the first person then we have to do 1000 of storage updation which is too expensive. so my question is how to do the above process in an efficient manner and can we have alternatives to arrays for the current scenario?
2 Answers
Why to reinvent the wheel (linked list)?? We have mappings & structs both are efficient in retrieving as well as in updating structured organised data. Since we're using solidity, it provides convenient in which mode we wanna access our data read-only Or read-write.
You just need to map appropriate structured data into mappings with all crucial info.
You can perform CRUD, whenever you want to. Accord... To your example... Create when someone signed up, read to check if he/she is single Or got a partner, update when they date, delete when you think.
You can use web: solidity-by-example, if you wanna play around with mappings and structs.
;`)
-
yes, structs and mappings can be used for the crud purpose but here in this situation I want to give a recommendation for the best match and for that purpose, we have to traverse the list from the start. Sep 29 at 7:10
-
"How to make a Linked List?" can shed some light to my idea... How we make a Linked List? Generally we link a node to the nodes around it, previous as well as next and if there's no previous node, we make it head & vice-versa. A Mapping in solidity is doing exactly this but in more efficient way. Please look at this example:
solidity struct PartnersData { // data type 1 // data type 2 // data type 3 // ... // another mapping type; // another struct type; } mapping(address partner1 => mapping(address partner2 => PartnersData)) public partners;
Sep 30 at 20:07 -
Oh yes, I searched for the linked list and you are correct we will use struct and mapping both for this purpose to be traversed. here is LInked list implementation. Oct 2 at 10:08
You shouldn't use arrays for this, for the reasons you mentioned.
Just switch to some other data storage pattern. For example linked lists should work just fine - additions and deletion are cheap.
-
Yes, the linked list is the perfect option for this situation. It will save us a lot of gas. Sep 29 at 7:12