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?