3

I'm reading the documentation right now: https://solidity.readthedocs.io/en/v0.5.3/style-guide.html

And it shows the right way to order functions, layout and so on... But there is no information how to order imports as well as fields inside a contract. I have no idea if changing imports order can affect the code or gas, but I made special folders and changed orders in every file's import to:

  1. interfaces [a-z]
  2. libraries [a-z]
  3. abstracts [a-z]
  4. contracts [a-z]

And each of them alphabetically and it looks more clean now. Hope this isn't anyhow wrong?

But going back to the contracts' fields - Should I order them anyhow I like, by importance or alphabetically? And can the different order affect the gas cost?

1 Answer 1

2

The fields of a contract can contain data which is permanently stored across function calls meaning that the field values are stored in the Ethreum Virtual Machine's (EVM) storage. I have been unable to find documentation on this but an Ethereum data analyst explained to me that field names are mapped to storage addresses through the use of the Keccak256(fieldName). A storage address is simply a number between 0 and 2^256. So the storage address on which a field value is stored is determined by what you name it but it is not affected by which order it is written in the source code. In general, the compiled code is not affected by the ordering of your fields or your functions. This means that the gas cost is also not affected by this.

There is, however, one place where you can save a little bit of gas by naming your functions cleverly. When a contract is called, the EVM finds the function through a jump table and the available functions in the smart contracts are ordered alphabetically by keccak256(<functionName>([typeOfFirstFunctionArgument][,typeOfSecondFunctionArgument][, ...])). So you could save a bit gas (between 10 and 1000 by my calculations) on each function call by naming your functions such that their hash values are ordered by how much they are used. This will ensure that fewer EVM instructions are executed when you call the most used functions is your contract. To see how the jump table works, have a look at What is the program counter at the start of an Ethereum method execution?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.