0

Which of the two is more efficient. Assuming I have this,

uint[] public availableRooms = [1,2,3,4,5,6,7]; 

And I need to know whether 5 is present in the array above. Which of the two is more efficient and can you help with how to do that with mapping?

Edit.

Based on the comments by users, a mapping will be the best way to find out if an element exists or not. So I changed the code into something like this

mapping (uni256 => bool); 

And in the constructor function, I constructor all instances of my availableRooms

constructor (){
availableRooms[1] = true;
availableRooms[2] = true;
availableRooms[3] = true;
availableRooms[4] = true;
availableRooms[5] = true;
availableRooms[6] = true;
availableRooms[7] = true;
}

And now to find out if the room really exist, all I have to do is

availableRooms[5] ; 
1
  • Iterating in solidity is very expensive and also limited to max number until u go out of gas. Mapping cannot be iterated easily u need to use some weird tricks to do that. Maybe the best way is to see the openZeppelin library contracts and see how are they handling iterations and arrays. I remember the erc721enumaration contract of them have something like that or need something like that
    – Majd TL
    Commented Apr 3, 2022 at 15:54

1 Answer 1

0

Yeah you can do this easy with a map.

mapping(uint8 => bool) public availableRooms;

uint8 is a number of the room. bool is a false/true , depending on if the room is available.

If you want to check if room number 5 is available you just need to call the map.

availableRooms [5]; //And you will get true or false

2
  • Does that mean, I shouldn't put in an array? Or I should create a mapping that has the same identification as the array?
    – Scyre27
    Commented Apr 3, 2022 at 18:26
  • If you wish to know if an element is in the list. Then mapping is the way to go. Way more efficient. Because in a list you would have to iterate over it and compare elements until you find a match.
    – Sky
    Commented Apr 4, 2022 at 8:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.