I'm trying to optimize some code and am going through some triggers. I'm wondering if there is a performance difference between
- running three methods in series – and in each one, I loop over
Trigger.new twice to pull an Id and then update the record from the
parent record – and
- combining the methods and looping only twice, but doing more script
statements in each loop iteration
The total script statements executed will be identical. This question is specifically if the number of loops executing those script statements should have an effect on application speed.
In general less loops is better, as this can lead to better chances to not thrash the L2 cache on the CPU, however there are so many levels between there and your apex code that the odds of you actually seeing any measurable difference is nil.
For triggers, performance is totally dominated by db access by a large margin, so that's the best place to concentrate on perf (make as few db calls as possible, access as little db data as possible, things that the governor limits already incentives you to do).
For apex code that's not touching the db,and doing approx the same number of script statements, don't sweat it, pick the version that's the most understandable/maintainable.