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
CarlBCarlB 

Apex constructors taking a lot of time

Hello.

I have written a batch process and it keeps failing with "Apex CPU time limit exceeded".

I used the Developer Console to profile the batch process and I am finding that the problem is with Apex constructors.

My batch contains 1000 records and I am wrapping each record in an Apex class.  The constructor for each class instance is taking at least 0.20 (milliseconds, I presume - although the Developer Console isn't clear).

This is a substantial chunk of the processing time.  Now, my constructor isn't doing any processing, beyond storing the record passed in as an argument.

Can anyone suggest why the constructor is soaking up so much time and what I can do about it?

Thanks,

Carl


 
ManojjenaManojjena
Hi CarlB,
is it possible to post your code ,I think your code needs to optimise .If possibel post your code we can optimise your code .
Thnaks
Manoj
CarlBCarlB
Hello.

I have done a bit more digging (the code is spread across a couple of managed packages, which makes debugging somewhat more difficult).  It seems that the delay is caused by using Type.newInstance(), which is taking most of the 0.2 milliseconds.

Why is that method so slow and is there anything I can do?

Regardsm

Carl
 
CarlBCarlB
Hello.

A further update - I re-wrote my code to avoid the multiple calls to Type.newInstance(), but it is just as slow.  Constructing 200 object instances is taking a significant amount of time.

Could the issue be that the code is spread over multiple managed packages?

Carl
 
CarlBCarlB
Hello.

Thinking about it a bit more, and having run a few more tests, the issue may be nothing to do with the constructor.

My class, in my base managed package, looks like this:
 
global abstract with sharing class BaseDataObject implements IDataObject {  

	private SObject m_Record;
	
	global BaseDataObject (SObject p_Record) {
		setRecord(p_Record);
	}

	global BaseDataObject () {
	}
	
	global virtual SObject getRecord() {
		return m_Record;
	}

	global virtual void setRecord(SObject p_Record) {
		m_Record = p_Record;
	}

	.
	.
	.
}

According to the Salesforce profiler, it is the call to setRecord(...) that is taking the time.  Also, subsequent calls to getRecord() take far longer than I would expect (about 10 milliseconds).

Can anyone think of a reason why this should be?

Carl