21

AFAIK there are 3 hash functions to choose from in solidity (sha3, sha256, and ripemd). sha3 is native while the others use precompiled contracts.

Which one of these is cheapest (in terms of gas)?

  • Your questions is slightly ambiguous. You could improve your question by specifying what you mean with "cheap". I assume you mean "which hashing algorithm has the lowest gas cost?" (Cheap can also mean in terms of computational power). – Jeffrey W. Apr 20 '16 at 7:58
  • @JeffreyW. done – Aakil Fernandes Apr 20 '16 at 12:31
20

keccak256 (new alias for sha3) is cheapest.

Source: Yellow Paper

Appendix G mentions the gas cost of sha3 is:

  • 30 gas + 6 gas for each word (rounded up) for input data to a SHA3 Keccak-256 operation.

Appendix E has the costs for the others.

sha256 (SHA2-256) costs:

  • 60 gas + 12 gas for each word (rounded up) for input data to a SHA2-256 operation.

ripemd is even more expensive:

  • 600 gas + 120 gas for each word (rounded up) for input data to a RIPEMD-160 operation.
  • 1
    It's worth noting that calls to the sha3 built-in function (as opposed to the assembly directive) currently appear to create a contract invocation in Solidity, which is much more expensive than it needs to be. – Nick Johnson Apr 20 '16 at 9:52
  • @NickJohnson Sounds like a good question to ask if it is invoking a contract. (I kept my answer to the Yellow Paper, since values in an empirical, implementation dependent answer could change over time.) – eth Apr 21 '16 at 10:33
  • @NickJohnson how do we know how we're calling it? is it the difference between blah = sha3(blah blah) and assembly { blah = sha3(blahblahblah) } ? – bekah Nov 28 '16 at 10:19
  • @bekah That's right; but how it works may well have changed since I wrote that comment. – Nick Johnson Nov 28 '16 at 17:56
  • 3
    Can someone confirm if this is still the case? – Moe Elsharif May 3 '18 at 15:51

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.