Solidity code performance is strictly tied to the gas metering costs as found in the Yellow Paper. As such, gas optimization both borrows from and extends traditional optimization techniques. This guide covers how gas usage of certain functions can be reliably identified and reduced.
Given the existence of a GAS opcode, there is no bulletproof way of estimating the gas consumption of a given function. First, you should study the function and determine inputs that could result in more excessive gas usage. These include:
With candidate inputs in mind and represented in test cases, the following techniques can be used:
As for gas optimization, we can recommend this handy guide from Blake West. One thing we will add is that for opcode level gas optimization, you should use an opcode level profiler such as in the Auditless Transaction Debugger.