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?

Is the capacitor drawn or wired wrongly?

Credit card offering 0.5 miles for every cent rounded up. Too good to be true?

Topological spaces which are not pseudometrizable.

What is a simple, physical situation where complex numbers emerge naturally?

Relativistic resistance transformation

How to provide realism without making readers think grimdark

Can a helicopter mask itself from radar?

Accidentally cashed a check twice

Can those paralyzed by the Hold Person spell be forcibly moved?

Why use water tanks from a retired Space Shuttle?

Should we freeze the number of people coming in to the study for Kaplan-Meier test

Beginner's snake game using PyGame

Why does a helium balloon rise?

If a problem only occurs randomly once in every N times on average, how many tests do I have to perform to be certain that it's now fixed?

Unconventional Opposites

Is there a term for this?

Is /home directory in root partition mapped to /home partition

Is there a rule that prohibits us from using 2 possessives in a row?

Can a class take a different class's spell in their ritual book?

Is it grammatical to use "car" like this?

Homophone fills the blanks

Is it OK to bring delicacies from hometown as tokens of gratitude for an out-of-town interview?

Can an old DSLR be upgraded to match modern smartphone image quality

When leasing/renting out an owned property, is there a standard ratio between monthly rent and the mortgage?



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

112k19125265




112k19125265







  • 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

272k14220472




272k14220472







  • 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

Wikipedia:Vital articles Мазмуну Biography - Өмүр баян Philosophy and psychology - Философия жана психология Religion - Дин Social sciences - Коомдук илимдер Language and literature - Тил жана адабият Science - Илим Technology - Технология Arts and recreation - Искусство жана эс алуу History and geography - Тарых жана география Навигация менюсу

Bruxelas-Capital Índice Historia | Composición | Situación lingüística | Clima | Cidades irmandadas | Notas | Véxase tamén | Menú de navegacióneO uso das linguas en Bruxelas e a situación do neerlandés"Rexión de Bruxelas Capital"o orixinalSitio da rexiónPáxina de Bruselas no sitio da Oficina de Promoción Turística de Valonia e BruxelasMapa Interactivo da Rexión de Bruxelas-CapitaleeWorldCat332144929079854441105155190212ID28008674080552-90000 0001 0666 3698n94104302ID540940339365017018237

What should I write in an apology letter, since I have decided not to join a company after accepting an offer letterShould I keep looking after accepting a job offer?What should I do when I've been verbally told I would get an offer letter, but still haven't gotten one after 4 weeks?Do I accept an offer from a company that I am not likely to join?New job hasn't confirmed starting date and I want to give current employer as much notice as possibleHow should I address my manager in my resignation letter?HR delayed background verification, now jobless as resignedNo email communication after accepting a formal written offer. How should I phrase the call?What should I do if after receiving a verbal offer letter I am informed that my written job offer is put on hold due to some internal issues?Should I inform the current employer that I am about to resign within 1-2 weeks since I have signed the offer letter and waiting for visa?What company will do, if I send their offer letter to another company