Most efficient way to switch on SObjectType?Efficient way to create master-detail recordsChecking CRUD for Static SobjectTypeMost efficient way to transform AggregateResults to String, Object MapsMost Efficient Method to Convert Set Type?Writting efficient trigger wayMost efficient way to insert test records for every Opportunity stageNull Pointer if sObjectType isn't CaseGood approach to making switch on string values case insensitive?Get sObjectType by ExternalIDHow can I access variable in switch case outside of switch block?

Why are GND pads often only connected by four traces?

Need to read my home electrical Meter

My players want to grind XP but we're using milestone advancement

Is my plasma cannon concept viable?

Why did Theresa May offer a vote on a second Brexit referendum?

Can I install a back bike rack without attachment to the rear part of the frame?

Dad jokes are fun

Is there a context where the expression `a.b::c` makes sense?

Are there any German nonsense poems (Jabberwocky)?

Is it legal to meet with potential future employers in the UK, whilst visiting from the USA

The art of clickbait captions

How was Daenerys able to legitimise this character?

Is it possible to remotely hack the GPS system and disable GPS service worldwide?

How to deal with a colleague who is being aggressive?

Python program for a simple calculator

What could a self-sustaining lunar colony slowly lose that would ultimately prove fatal?

Python program to take in two strings and print the larger string

Dealing with spaghetti codebase, manager asks for things I can't deliver

Why A=2 and B=1 in the call signs for Spirit and Opportunity?

Of strange atmospheres - the survivable but unbreathable

What's difference between "depends on" and "is blocked by" relations between issues in Jira next-gen board?

Is it truly impossible to tell what a CPU is doing?

Is it possible to prohibit all prohibitable schools of magic with a single character?

Why are Stein manifolds/spaces the analog of affine varieties/schemes in algebraic geometry?



Most efficient way to switch on SObjectType?


Efficient way to create master-detail recordsChecking CRUD for Static SobjectTypeMost efficient way to transform AggregateResults to String, Object MapsMost Efficient Method to Convert Set Type?Writting efficient trigger wayMost efficient way to insert test records for every Opportunity stageNull Pointer if sObjectType isn't CaseGood approach to making switch on string values case insensitive?Get sObjectType by ExternalIDHow can I access variable in switch case outside of switch block?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








6















It is a bit odd we can't evaluate a switch statement directly on SObjectType, so I am trying to determine conclusively which workaround is the most efficient.



Just to verify, I tried to compile this code:



void demo(SObjectType input)

switch on input

when Account.sObjectType
when else




And this code generates the error:




Schema.SObjectType is not a valid switch expression type




Bummer. There are workarounds however. The two most obvious that I have come up with:



void demoRecordInstantiation(SObjectType input)

switch on input.newSObject()

when Account a
when else


void demoStringTyping(SObjectType input)

switch on String.valueOf(input)

when 'Account'
when else




Maybe there are others, so if there is an obvious approach I have missed which performs better or is more readable/maintainable, let me know.



My question is, what approach offers the best performance? If I am calling this method many times in a loop, is the SObjectType.newSObject method resource intensive? Or calling String.valueOf(SObjectType)? Should I consider caching these values?










share|improve this question



















  • 1





    I will profile this question as time allows, but right now I am not able to perform an in depth analysis and would be happy for someone to beat me to the punch.

    – Adrian Larson
    May 17 at 15:52






  • 2





    i've used these workarounds myself and had to wash my hands afterwards. Let's hope that switch on SObjectType comes soon

    – cropredy
    May 17 at 16:54






  • 3





    I strongly prefer the former, as at least you maintain concrete object references.

    – Adrian Larson
    May 17 at 16:55


















6















It is a bit odd we can't evaluate a switch statement directly on SObjectType, so I am trying to determine conclusively which workaround is the most efficient.



Just to verify, I tried to compile this code:



void demo(SObjectType input)

switch on input

when Account.sObjectType
when else




And this code generates the error:




Schema.SObjectType is not a valid switch expression type




Bummer. There are workarounds however. The two most obvious that I have come up with:



void demoRecordInstantiation(SObjectType input)

switch on input.newSObject()

when Account a
when else


void demoStringTyping(SObjectType input)

switch on String.valueOf(input)

when 'Account'
when else




Maybe there are others, so if there is an obvious approach I have missed which performs better or is more readable/maintainable, let me know.



My question is, what approach offers the best performance? If I am calling this method many times in a loop, is the SObjectType.newSObject method resource intensive? Or calling String.valueOf(SObjectType)? Should I consider caching these values?










share|improve this question



















  • 1





    I will profile this question as time allows, but right now I am not able to perform an in depth analysis and would be happy for someone to beat me to the punch.

    – Adrian Larson
    May 17 at 15:52






  • 2





    i've used these workarounds myself and had to wash my hands afterwards. Let's hope that switch on SObjectType comes soon

    – cropredy
    May 17 at 16:54






  • 3





    I strongly prefer the former, as at least you maintain concrete object references.

    – Adrian Larson
    May 17 at 16:55














6












6








6


1






It is a bit odd we can't evaluate a switch statement directly on SObjectType, so I am trying to determine conclusively which workaround is the most efficient.



Just to verify, I tried to compile this code:



void demo(SObjectType input)

switch on input

when Account.sObjectType
when else




And this code generates the error:




Schema.SObjectType is not a valid switch expression type




Bummer. There are workarounds however. The two most obvious that I have come up with:



void demoRecordInstantiation(SObjectType input)

switch on input.newSObject()

when Account a
when else


void demoStringTyping(SObjectType input)

switch on String.valueOf(input)

when 'Account'
when else




Maybe there are others, so if there is an obvious approach I have missed which performs better or is more readable/maintainable, let me know.



My question is, what approach offers the best performance? If I am calling this method many times in a loop, is the SObjectType.newSObject method resource intensive? Or calling String.valueOf(SObjectType)? Should I consider caching these values?










share|improve this question
















It is a bit odd we can't evaluate a switch statement directly on SObjectType, so I am trying to determine conclusively which workaround is the most efficient.



Just to verify, I tried to compile this code:



void demo(SObjectType input)

switch on input

when Account.sObjectType
when else




And this code generates the error:




Schema.SObjectType is not a valid switch expression type




Bummer. There are workarounds however. The two most obvious that I have come up with:



void demoRecordInstantiation(SObjectType input)

switch on input.newSObject()

when Account a
when else


void demoStringTyping(SObjectType input)

switch on String.valueOf(input)

when 'Account'
when else




Maybe there are others, so if there is an obvious approach I have missed which performs better or is more readable/maintainable, let me know.



My question is, what approach offers the best performance? If I am calling this method many times in a loop, is the SObjectType.newSObject method resource intensive? Or calling String.valueOf(SObjectType)? Should I consider caching these values?







apex bestpractice performance sobjecttype switch-case






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited May 17 at 16:47







Adrian Larson

















asked May 17 at 15:51









Adrian LarsonAdrian Larson

113k19124264




113k19124264







  • 1





    I will profile this question as time allows, but right now I am not able to perform an in depth analysis and would be happy for someone to beat me to the punch.

    – Adrian Larson
    May 17 at 15:52






  • 2





    i've used these workarounds myself and had to wash my hands afterwards. Let's hope that switch on SObjectType comes soon

    – cropredy
    May 17 at 16:54






  • 3





    I strongly prefer the former, as at least you maintain concrete object references.

    – Adrian Larson
    May 17 at 16:55













  • 1





    I will profile this question as time allows, but right now I am not able to perform an in depth analysis and would be happy for someone to beat me to the punch.

    – Adrian Larson
    May 17 at 15:52






  • 2





    i've used these workarounds myself and had to wash my hands afterwards. Let's hope that switch on SObjectType comes soon

    – cropredy
    May 17 at 16:54






  • 3





    I strongly prefer the former, as at least you maintain concrete object references.

    – Adrian Larson
    May 17 at 16:55








1




1





I will profile this question as time allows, but right now I am not able to perform an in depth analysis and would be happy for someone to beat me to the punch.

– Adrian Larson
May 17 at 15:52





I will profile this question as time allows, but right now I am not able to perform an in depth analysis and would be happy for someone to beat me to the punch.

– Adrian Larson
May 17 at 15:52




2




2





i've used these workarounds myself and had to wash my hands afterwards. Let's hope that switch on SObjectType comes soon

– cropredy
May 17 at 16:54





i've used these workarounds myself and had to wash my hands afterwards. Let's hope that switch on SObjectType comes soon

– cropredy
May 17 at 16:54




3




3





I strongly prefer the former, as at least you maintain concrete object references.

– Adrian Larson
May 17 at 16:55






I strongly prefer the former, as at least you maintain concrete object references.

– Adrian Larson
May 17 at 16:55











1 Answer
1






active

oldest

votes


















5














The when values must be literals, so you cannot use String.valueOf as demonstrated in your second example. That said, using String.valueOf is approximately 10% more efficient when using literal string values:



Long t3, t2, t1 = datetime.now().gettime();
for(Integer i = 0; i < 100000; i++)
sobjecttype a = account.sobjecttype;
switch on a.newsobject()
when account ac


when contact co




t2 = datetime.now().gettime();
for(Integer i = 0; i < 100000; i++)
sobjecttype a = account.sobjecttype;
switch on string.valueof(a)
when 'Account'


when 'Contact'




t3 = datetime.now().gettime();
system.debug(t3-t2);
system.debug(t2-t1);


That said, it appears that the actual performance difference is insignificant (less than 0.008 ms per call), so unless you need the performance, choose whichever works best for you.



As an aside, make sure you comment this code for followup later. It has been said salesforce.com would like to include other data types in future releases, and this may include the sObjectType data type as well.






share|improve this answer


















  • 2





    Huh, good to know on that last paragraph. Would be nice to see them add support for this one, as it seems like it would be a very common use case.

    – Adrian Larson
    May 17 at 16:46






  • 2





    @AdrianLarson Yes, I've had a number of times since switch came out that I wished I could use sObjectType. It'd be the most efficient version of the switch statement for its use case.

    – sfdcfox
    May 17 at 16:48











  • On the plus side, this post is a likely canary if I fail to catch it in the release notes when they do make this change. Seems fair to assume when not if here.

    – Adrian Larson
    May 17 at 16:50












Your Answer








StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "459"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsalesforce.stackexchange.com%2fquestions%2f262841%2fmost-efficient-way-to-switch-on-sobjecttype%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









5














The when values must be literals, so you cannot use String.valueOf as demonstrated in your second example. That said, using String.valueOf is approximately 10% more efficient when using literal string values:



Long t3, t2, t1 = datetime.now().gettime();
for(Integer i = 0; i < 100000; i++)
sobjecttype a = account.sobjecttype;
switch on a.newsobject()
when account ac


when contact co




t2 = datetime.now().gettime();
for(Integer i = 0; i < 100000; i++)
sobjecttype a = account.sobjecttype;
switch on string.valueof(a)
when 'Account'


when 'Contact'




t3 = datetime.now().gettime();
system.debug(t3-t2);
system.debug(t2-t1);


That said, it appears that the actual performance difference is insignificant (less than 0.008 ms per call), so unless you need the performance, choose whichever works best for you.



As an aside, make sure you comment this code for followup later. It has been said salesforce.com would like to include other data types in future releases, and this may include the sObjectType data type as well.






share|improve this answer


















  • 2





    Huh, good to know on that last paragraph. Would be nice to see them add support for this one, as it seems like it would be a very common use case.

    – Adrian Larson
    May 17 at 16:46






  • 2





    @AdrianLarson Yes, I've had a number of times since switch came out that I wished I could use sObjectType. It'd be the most efficient version of the switch statement for its use case.

    – sfdcfox
    May 17 at 16:48











  • On the plus side, this post is a likely canary if I fail to catch it in the release notes when they do make this change. Seems fair to assume when not if here.

    – Adrian Larson
    May 17 at 16:50
















5














The when values must be literals, so you cannot use String.valueOf as demonstrated in your second example. That said, using String.valueOf is approximately 10% more efficient when using literal string values:



Long t3, t2, t1 = datetime.now().gettime();
for(Integer i = 0; i < 100000; i++)
sobjecttype a = account.sobjecttype;
switch on a.newsobject()
when account ac


when contact co




t2 = datetime.now().gettime();
for(Integer i = 0; i < 100000; i++)
sobjecttype a = account.sobjecttype;
switch on string.valueof(a)
when 'Account'


when 'Contact'




t3 = datetime.now().gettime();
system.debug(t3-t2);
system.debug(t2-t1);


That said, it appears that the actual performance difference is insignificant (less than 0.008 ms per call), so unless you need the performance, choose whichever works best for you.



As an aside, make sure you comment this code for followup later. It has been said salesforce.com would like to include other data types in future releases, and this may include the sObjectType data type as well.






share|improve this answer


















  • 2





    Huh, good to know on that last paragraph. Would be nice to see them add support for this one, as it seems like it would be a very common use case.

    – Adrian Larson
    May 17 at 16:46






  • 2





    @AdrianLarson Yes, I've had a number of times since switch came out that I wished I could use sObjectType. It'd be the most efficient version of the switch statement for its use case.

    – sfdcfox
    May 17 at 16:48











  • On the plus side, this post is a likely canary if I fail to catch it in the release notes when they do make this change. Seems fair to assume when not if here.

    – Adrian Larson
    May 17 at 16:50














5












5








5







The when values must be literals, so you cannot use String.valueOf as demonstrated in your second example. That said, using String.valueOf is approximately 10% more efficient when using literal string values:



Long t3, t2, t1 = datetime.now().gettime();
for(Integer i = 0; i < 100000; i++)
sobjecttype a = account.sobjecttype;
switch on a.newsobject()
when account ac


when contact co




t2 = datetime.now().gettime();
for(Integer i = 0; i < 100000; i++)
sobjecttype a = account.sobjecttype;
switch on string.valueof(a)
when 'Account'


when 'Contact'




t3 = datetime.now().gettime();
system.debug(t3-t2);
system.debug(t2-t1);


That said, it appears that the actual performance difference is insignificant (less than 0.008 ms per call), so unless you need the performance, choose whichever works best for you.



As an aside, make sure you comment this code for followup later. It has been said salesforce.com would like to include other data types in future releases, and this may include the sObjectType data type as well.






share|improve this answer













The when values must be literals, so you cannot use String.valueOf as demonstrated in your second example. That said, using String.valueOf is approximately 10% more efficient when using literal string values:



Long t3, t2, t1 = datetime.now().gettime();
for(Integer i = 0; i < 100000; i++)
sobjecttype a = account.sobjecttype;
switch on a.newsobject()
when account ac


when contact co




t2 = datetime.now().gettime();
for(Integer i = 0; i < 100000; i++)
sobjecttype a = account.sobjecttype;
switch on string.valueof(a)
when 'Account'


when 'Contact'




t3 = datetime.now().gettime();
system.debug(t3-t2);
system.debug(t2-t1);


That said, it appears that the actual performance difference is insignificant (less than 0.008 ms per call), so unless you need the performance, choose whichever works best for you.



As an aside, make sure you comment this code for followup later. It has been said salesforce.com would like to include other data types in future releases, and this may include the sObjectType data type as well.







share|improve this answer












share|improve this answer



share|improve this answer










answered May 17 at 16:41









sfdcfoxsfdcfox

271k13219471




271k13219471







  • 2





    Huh, good to know on that last paragraph. Would be nice to see them add support for this one, as it seems like it would be a very common use case.

    – Adrian Larson
    May 17 at 16:46






  • 2





    @AdrianLarson Yes, I've had a number of times since switch came out that I wished I could use sObjectType. It'd be the most efficient version of the switch statement for its use case.

    – sfdcfox
    May 17 at 16:48











  • On the plus side, this post is a likely canary if I fail to catch it in the release notes when they do make this change. Seems fair to assume when not if here.

    – Adrian Larson
    May 17 at 16:50













  • 2





    Huh, good to know on that last paragraph. Would be nice to see them add support for this one, as it seems like it would be a very common use case.

    – Adrian Larson
    May 17 at 16:46






  • 2





    @AdrianLarson Yes, I've had a number of times since switch came out that I wished I could use sObjectType. It'd be the most efficient version of the switch statement for its use case.

    – sfdcfox
    May 17 at 16:48











  • On the plus side, this post is a likely canary if I fail to catch it in the release notes when they do make this change. Seems fair to assume when not if here.

    – Adrian Larson
    May 17 at 16:50








2




2





Huh, good to know on that last paragraph. Would be nice to see them add support for this one, as it seems like it would be a very common use case.

– Adrian Larson
May 17 at 16:46





Huh, good to know on that last paragraph. Would be nice to see them add support for this one, as it seems like it would be a very common use case.

– Adrian Larson
May 17 at 16:46




2




2





@AdrianLarson Yes, I've had a number of times since switch came out that I wished I could use sObjectType. It'd be the most efficient version of the switch statement for its use case.

– sfdcfox
May 17 at 16:48





@AdrianLarson Yes, I've had a number of times since switch came out that I wished I could use sObjectType. It'd be the most efficient version of the switch statement for its use case.

– sfdcfox
May 17 at 16:48













On the plus side, this post is a likely canary if I fail to catch it in the release notes when they do make this change. Seems fair to assume when not if here.

– Adrian Larson
May 17 at 16:50






On the plus side, this post is a likely canary if I fail to catch it in the release notes when they do make this change. Seems fair to assume when not if here.

– Adrian Larson
May 17 at 16:50


















draft saved

draft discarded
















































Thanks for contributing an answer to Salesforce Stack Exchange!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsalesforce.stackexchange.com%2fquestions%2f262841%2fmost-efficient-way-to-switch-on-sobjecttype%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Get product attribute by attribute group code in magento 2get product attribute by product attribute group in magento 2Magento 2 Log Bundle Product Data in List Page?How to get all product attribute of a attribute group of Default attribute set?Magento 2.1 Create a filter in the product grid by new attributeMagento 2 : Get Product Attribute values By GroupMagento 2 How to get all existing values for one attributeMagento 2 get custom attribute of a single product inside a pluginMagento 2.3 How to get all the Multi Source Inventory (MSI) locations collection in custom module?Magento2: how to develop rest API to get new productsGet product attribute by attribute group code ( [attribute_group_code] ) in magento 2

Category:9 (number) SubcategoriesMedia in category "9 (number)"Navigation menuUpload mediaGND ID: 4485639-8Library of Congress authority ID: sh85091979ReasonatorScholiaStatistics

Magento 2.3: How do i solve this, Not registered handle, on custom form?How can i rewrite TierPrice Block in Magento2magento 2 captcha not rendering if I override layout xmlmain.CRITICAL: Plugin class doesn't existMagento 2 : Problem while adding custom button order view page?Magento 2.2.5: Overriding Admin Controller sales/orderMagento 2.2.5: Add, Update and Delete existing products Custom OptionsMagento 2.3 : File Upload issue in UI Component FormMagento2 Not registered handleHow to configured Form Builder Js in my custom magento 2.3.0 module?Magento 2.3. How to create image upload field in an admin form