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.
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
bytesin 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,
string, but if you know the length to expect, you can call them using inline assembly.
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.
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.