DISCLAIMER: Use this trick at your own risk. Do not do this, unless you absolutely have to.
Some time ago I had to figure out why one of the custom services was slow. It took like 30+ seconds to return a dozen of trade agreements for a customer.
It turned out the SysExtension framework tried to collect data about classes through reflection, and it did that multiple times in the same session.
The issue may be reproduced with this runnable class. Here, we instantiate instances of 4 different classes. The class constructors use SysExtension framework for figuring out which class type to build.
If running the class the first time, the output would look something like this:
SalesLineType::construct: 13610 ms
SalesSummaryFields::construct: 1968 ms
SalesQuantity::construct: 2078 ms
TradeModuleType::newFromModule: 3406 ms
After System administration -> Setup -> Refresh elements, the time would drop to:
SalesLineType::construct: 1735 ms
SalesSummaryFields::construct: 1781 ms
SalesQuantity::construct: 1641 ms
TradeModuleType::newFromModule: 1656 ms
But still, almost 2 seconds for every single class instance is too much.
The following change can fix this issue by skipping metadata collection, if it is already done:
This code does the following: if the reflection is already collected (reflectionDataEnumerator.moveNext() returns "true"), we throw an exception of a type, that will most likely never be thrown from the "next populateFromMetadata();" itself. Then, we catch the exception, but that also means the "next" statement is skipped and the reflection cache data is not built from scratch again.
After this change, the runnable class output looks like this:
SalesLineType::construct: 1657 ms
SalesSummaryFields::construct: 218 ms
SalesQuantity::construct: 125 ms
TradeModuleType::newFromModule: 157 ms
It is important, that this "skip" is only done when there is no transaction scope around, otherwise it would abort the transaction, therefore the check for ttsLevel. So, this trick will basically improve performance of certain "read" scenarios, but in order to improve performance for "write" scenarios, MS has to provide a fix.