I need to create a lookup table [uint -> uint] that is constant.

Constant mappings or switch-case are not available in solidity. Are pure functions full of if-else the only option?

Any better suggestion?

Update Ideally, I would like an option that minimizes gas utilization

  • It seems from discussion below that this question is about gas optimization.
    – user19510
    Jan 2 '19 at 23:48

I don't see a dilemma.

You can have a mapping:

mapping(uint => uint) public myMap;

You can populate some locations in the constructor or elsewhere:

constructor() public {
  myMap[1] = 101;
  myMap[2] = 201;

That gives you a simple view function (myMap(uint) public view returns(uint)) that returns the number stored at an index.

You can also make view functions full of if/else if that's the best approach for your use-case.

Elaborate on the question with some hints about what you want to accomplish and possibly more specific guidance will be possible.

Hope it helps.

  • Well, clearly I want to minimize gas. What do you think would be more efficient?
    – Juan Leni
    Jan 2 '19 at 23:14
  • please note that the requirement is constant mapping to save gas cost of sload. This solution only saves the extra call to update storage values. Sep 3 '20 at 9:44

The else-if function is by far less efficient that mapping in case of sparse data if there are not special criteria for searching.

If, on the contrary, you fill all the holes in the range of interest, a simple array is the best solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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