What is the most cost effective way to compare to arrays eg. uint arrays in solidity. Running a for loop takes too much gas.


I suspect that a for loop is the most efficient way. But depending on what you're doing, perhaps you can do the work off chain.

For example, say there are two users: Alice and Bob. There are also two arrays: array1 and array2. If the two arrays are equal, Alice should be paid some amount. If the two arrays are not equal, Bob should be paid some amount. The smart contract logic can now be quite simple: by default, Alice will get paid after 24 hours. If Bob wants to get paid, he must call a function in the smart contract telling it which element of the two arrays is different. The smart contract can easily verify this in constant time and pay Bob if he's telling the truth.


If 2 array is not the same set but some element is the same and u want to check it then the only way is loop, If you want to compare 2 array which is the same set you can use keccak256 compare of 2 array: keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b)));

But if you want to check the same element then why not use view and return the result because it doesnt change the state of the blockchain so it doesn't take eth.

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.