28

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)?

2
  • 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.
    Commented Apr 20, 2016 at 7:58
  • @JeffreyW. done
    – Akhil F
    Commented Apr 20, 2016 at 12:31

1 Answer 1

30

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.
9
  • 2
    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. Commented Apr 20, 2016 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
    Commented Apr 21, 2016 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
    Commented Nov 28, 2016 at 10:19
  • 3
    Can someone confirm if this is still the case? Commented May 3, 2018 at 15:51
  • 1
    @TharinduMadushanka Do you mean ethereum.stackexchange.com/questions/550/… ?
    – eth
    Commented Jul 30, 2021 at 0:07

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.