function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Maros Sitko1Maros Sitko1 

CPU Time exceeded in test classes

Hi, has anyone find that some test classes started fail with CPU Time exceeded message without chnaging anything? We have started get this error 2 days ago in sandboxed, and yesterday also in production - without any code changes!
For second customer, test class fail when we have just Test.DataLoad() function in test method and one simple trigger. When we have 175 lines in CSV it failed, with 150 not. Trigger is bulkified correcly, and test class has been successful week ago - last time of development. We receing error:
System.SObjectException: common.apex.runtime.impl.ExecutionException: Apex CPU time limit exceeded
and in traceroute : Class.System.Test.loadData: line 53, column 1 what is system method!!!
I started to think, that it was caused by some Spring '16 Patch maybe https://success.salesforce.com/issues_releases_view?release=200005000 , but there is nothing about changing which cought error.
Mahesh DMahesh D
HI Maros,

If we can check your code, we can able to suggest some modifications to improve the performance of the code.

Fixing a common cause of System.LimitException: Apex CPU time limit exceeded


When developing code, automated unit tests and interactive testing naturally tend to use small numbers of objects. As the number of objects increases, the execution time has to increase in proportion – linearly. But it is all too easy to introduce code where the execution time grows as the square of the number of objects or the cube of the number of objects. (See e.g. Time complexity for some background.) For example, even with 100 objects, code that takes 100ms for the linear case, takes 10s for the squared case and 1,000s for the cubed case. So for the squared or cubed cases

System.LimitException: Apex CPU time limit exceeded

exceptions can result with even modest numbers of objects.
Is this governor limit a good thing? On the positive side, it forces a bad algorithm to be replaced by a better one. But on the negative side, your customer is stuck unable to work until you can deliver a fix to them. Some sort of alarm and forgiveness from the platform for a while would be more helpful.
Here is a blatant example of the problem (assuming all the collections include large numbers of objects):
 
// Linear - OK
for (Parent__c p : parents) {
    // Squared - problem
    for (Child__c c : children) {
        // Cubed - big problem
        for (GrandChild__c bc : grandChildren) {
            // ...
        }
    }
}

So review all nested loops carefully. Sometimes the problem is hidden, with one loop in one method or class and another loop in another method or class, and so harder to find.
Often the purpose of the loops is just to find the objects/object in one collection that match an object in another collection. There are two contexts that require two different approaches (though in more complicated cases the approaches can be combined) to fix the problem or better to avoid it in the first place:
  • In e.g. a controller where the query is explicit, a parent and child can be queried together with direct relationship references available using a relationship query.
  • In a trigger, no __r collections are populated, so maps have to be used. A map allows a value to be looked up without the cost of going through every entry in a list.
Here is how to fix the problem for the two contexts in parent-child relationships:
 
// Explicit SOQL context
for (Parent__c p : [
        select Name, (select Name from Childs__r)
        from Parent__c
        ]) {
    // Loop is over the small number of related Child__c not all of the Child__c
    for (Child__c c : p.Childs__r) {
        // ...
    }
}
 
 
// Trigger context
Map<Id, List<Child__c>> children = new Map<Id, List<Child__c>>();
for (Child__c c : [
        select Parent__c, Name
        from Child__c
        where Parent__c in Trigger.newMap.keySet()
        ]) {
    List<Child__c> l = children.get(c.Parent__c);
    if (l == null) {
        l = new List<Child__c>();
        children.put(c.Parent__c, l);
    }
    l.add(c);
}
for (Parent__c p : Trigger.new) {
    // Loop is over the small number of related Child__c not all of the Child__c
    if (children.containsKey(p.Id)) {
        for (Child__c c : children.get(p.Id) {
            // ...
        }
    }
}

And for the two contexts in child-parent relationships:
 
// Explicit SOQL context
for (Child__c c : [
        select Name, Parent__r.Name
        from Child__c
        ]) {
    // The one parent
    Parent__c p = c.Parent__r;
    if (p != null) {
        // ...
    }
}
 
 
// Trigger context
Set<Id> parentIds = new Set<Id>();
for (Child__c c : Trigger.new) {
    if (c.Parent__c != null) {
        parentIds.add(c.Parent__c);
    }
}
if (parentIds.size() > 0) {
    Map<Id, Parent__c> parents = new Map<Id, Parent__c>([
            select Id, Name
            from Parent__c
            where Id in :parentIds
            ]);
    for (Child__c c : Trigger.new) {
        // The one parent
        if (c.Parent__c != null) {
            Parent__c p = parents.get(c.Parent__c);
            if (p != null) {
                // ...
            }
        }
    }
}



Look into the below posts on the same issue:

http://salesforce.stackexchange.com/questions/22223/how-to-code-more-efficient-to-avoid-apex-cpu-time-limit-exceeded

http://stackoverflow.com/questions/25126270/need-help-to-overcome-apex-cpu-time-limit-exceeded-error

http://www.infallibletechie.com/2014/02/systemlimitexception-apex-cpu-time.html

http://salesforce.stackexchange.com/questions/47035/errorsystem-limitexception-apex-cpu-time-limit-exceeded

http://salesforce.stackexchange.com/questions/84160/apex-cpu-time-limit-exceeded-error-any-suggestions

https://developer.salesforce.com/forums/?id=906F00000005HZ2IAM

https://developer.salesforce.com/forums/?id=906F0000000AoRSIA0

https://developer.salesforce.com/forums/?id=906F000000093rCIAQ

https://force201.wordpress.com/2014/11/09/fixing-a-common-cause-of-system-limitexception-apex-cpu-time-limit-exceeded/

http://www.sfdc99.com/forums/topic/system-limitexception-apex-cpu-time-limit-exceeded-error-in-trigger/


Please do let me know if it helps you.

Regards,
Mahesh
Maros Sitko1Maros Sitko1
Hi, thank you for your long answer, but I am talking about thing, that everything worked one day, next day it failed without any changes (I also checked Audit Trail, if for example someone not created the code).
What you are writing about small number of test data at the beggining, is not true! You should test your code with at list with 200 records, ideal is 201, becuase if you test it with just 10 record, your code can failed during integration, which is make with bulk of 20 records by defualt! So the best practise it test with at least 200 records! (if you test with 201 records, your triggers run twice, so you can test your static variables too).

Maros
Ravi Prakash 41Ravi Prakash 41
Hey is your issue resolved