According to Donald Knuth actually "is the root of all evil". But this doesn't seem to hold true on the Force.com platform and its CPU time Limit.

After watching Paul Battisson's Faster Loops videos it seems we should NOT care about readable, short Apex code but have to add complexity and weird optimizations to get enough done inside the limits.

The platform seems not to optimize the code in ways e.g. the Java compiler does it.

But why aren't there official Apex best practices by Salesforce.com itself in the way: Optimize here or there?!

Whom would I turn to to find out where my code could be (dramatically) optimized?

  • 3
    FWIW, I'm working on some benchmarks. Some results are rather ... surprising.
    – sfdcfox
    Jun 6, 2015 at 16:27
  • 1
    In the summer 15 release notes it mentions that static string concatenation is optimized. It would be useful to know what other optimizations are occurring. Jun 6, 2015 at 19:44
  • 1
    Usually it's applying the right algorithm that makes the big difference e.g. loop and map vs loop inside loop. Apex executes in the JVM so gets a lot of the same speed ups that Java does. (But classes like StringBuilder are missing.)
    – Keith C
    Jun 7, 2015 at 13:24
  • 1
    Yeah painful. Support can up the log size and turn on detailed logging for your managed package code so you can figure out what is happening. In my code the problem has usually been hidden exponential cost code. For example, a method called per object and then a layer or two down another per object loop.
    – Keith C
    Jun 7, 2015 at 14:18
  • 1
    @RobertSösemann Have you used the Developer Console Profiling features (switch your perspective to "Analysis" then look under "Execution Overview" > "Timeline" for a start)? I've found this to be quite helpful in determining what parts of the execution (Apex, Workflow, Validation, etc.) are taking up the most relative time, and from there which sections of Apex are the most time consuming. Doesn't always mean there's much you can do to change it, though :)
    – zachelrath
    Jun 19, 2015 at 17:07