A lot of people have expressed excitement at the potential of using inline assembly in smart contracts. After seeing this comment on reddit I'm curious to see some basic (and more advanced, if you like) examples of how inline assembly may be used to save gas or otherwise augment efficiency.
3 Answers
As the author of that module, a few things that came up:
- Inline assembly allows you to read entire words (256 bits) from data types like
stringandbytesin a single operation. Solidity-stringutils uses that to do very fast string comparisons by doing subtraction on 32-byte chunks of the two strings being compared. Without assembly, you have to do this byte-by-byte. - Some operations aren't exposed in Solidity. For instance, the
sha3opcode takes a byte range in memory to hash, while the Solidity function of the same name takes a string. Thus, hashing part of a string would require costly string copying operations. With inline assembly, you can pass in a string and hash just the bit you care about. - Some things are flat out impossible without inline assembly. Solidity doesn't support getting return values from external functions that return variable length types like dynamic arrays,
bytesorstring, but if you know the length to expect, you can call them using inline assembly.
- 8,144
- 1
- 28
- 35
I know this is an old topic, but here's a couple of tutorials I put together to cover assembly in solidity:
Functional Assembly - https://www.youtube.com/watch?v=nkGN6GwkMzU
Instructional Assembly - https://www.youtube.com/watch?v=axZJ2NFMH5Q
I go into the benefits, disadvantages, examples and debugging assembly.
- 514
- 4
- 7
Well for one you can do things that you cannot do with traditional assembly...a perfect example is the new string utils setup per Nick Johnson. https://github.com/Arachnid/solidity-stringutils
The feature is fairly new, but whatever your imagination takes you to and whatever you deem useful, you can do in inline assembly per the requirements of the EVM. There's even something in the docs about it.
http://solidity.readthedocs.org/en/latest/control-structures.html#inline-assembly
- 1,710
- 9
- 15
RETURNDATASIZEandRETURNDATACOPYopcodes, we can query the code of a contract via<address>code, and much more. – Paul Razvan Berg Sep 05 '21 at 15:19