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

Akhil F
  • 1,928
  • 3
  • 19
  • 29
  • 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 07:58
  • @JeffreyW. done – Akhil F Apr 20 '16 at 12:31

1 Answers1

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.
eth
  • 85,679
  • 53
  • 285
  • 406
  • 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. – Nick Johnson Apr 20 '16 at 09: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 03 '18 at 15:51
  • sha3 is not exactly keccak256. Ethereum source code for keccak256 confirms it. – Tharindu Madushanka Jul 29 '21 at 11:11
  • 1
    @TharinduMadushanka Do you mean https://ethereum.stackexchange.com/questions/550/which-cryptographic-hash-function-does-ethereum-use ? – eth Jul 30 '21 at 00:07
  • Yes. Just to note that it's not same as sha3. "The Ethereum hashing function, keccak256, sometimes (erroneously) called sha3" https://github.com/ethereum/eth-hash – Tharindu Madushanka Jul 31 '21 at 03:54
  • @NickJohnson This does not appear to be the case anymore. I tried hashing something via keccak256(abi.encodePacked(...)) and via assembly {c := keccak256(add(encoded, 0x20), 40)}. The assembly version actually ended up costing 11 gas more. – UTF-8 Jul 12 '22 at 11:26