I'm looking to optimise my code because I keep getting the error:
Apex CPU time limit Exceeded
I understand this error, which means your apex code cannot be running for more than 10 seconds on the salesforce servers.
Now I have fixed my problem and I am no longer receiving the error, but when I analyse my code in the debug logs, I can see the Apex code is running for 34 seconds, so how is this not erroring?
For reference, here is my code:
public class TestApexCpuLimitVFPageController {
static List<Account> newAccounts = new List<Account>();
static List<Contact> newContacts = new List<Contact>();
static Map<string, Account> newAccountsMapByName = new Map<string, Account>();
public static void test()
{
Savepoint sp = Database.setSavepoint();
createAccounts();
createContacts();
matchContactWithAccount();
Database.rollback(sp);
}
static void matchContactWithAccount()
{
integer i = 0;
for (Contact c: newContacts)
{
Account acc = getAccountByName('test' + i);
//Account acc = newAccountsMapByName.get('test' + i);
i++;
c.AccountId = acc.Id;
}
update newContacts;
}
static Account getAccountByName(string accountName)
{
for (Account acc: newAccounts)
{
if (acc.Name == accountName)
{
return acc;
}
}
return null;
}
static void createContacts()
{
for (integer i = 0; i < 500; i++)
{
Contact newContact = new Contact(FirstName='first' + i, LastName='last' + i);
newContacts.add(newContact);
}
insert newContacts;
}
static void createAccounts()
{
for (integer i = 0; i < 500; i++)
{
Account newAccount = new Account(Name='test' + i);
newAccounts.add(newAccount);
newAccountsMapByName.put('test' + i, newAccount);
}
insert newAccountsMapByName.values();
}
}