tl;dr
This is almost certainly a micro-optimization.
Don't worry about it, you aren't running it enough times to make any significant impact on the CPU limit. If you are running into the CPU limit, there are certainly other places you should be looking to improve first
longer
This is something that's easy enough to benchmark on your own. A simple benchmark is to just run the code in a loop, and also run an "empty" loop so you can subtract the inherent loop time from whatever it is you're trying to measure.
Event evt = [SELECT Id, WhatId FROM Event WHERE What.Type = 'Opportunity' LIMIT 1]; Integer t1; Integer t2; Integer iterations = 10000; // Baseline loop cost with one declaration and assignment t1 = Limits.getCPUTime(); for(Integer i = 0; i < iterations; i++) { Boolean b = true; } t2 = Limits.getCPUTime(); System.debug((t2-t1) + ' cpu units'); // The thing we want to check t1 = Limits.getCPUTime(); for(Integer i = 0; i < iterations; i++) { Boolean b = evt.WhatId.getSObjectType().getDescribe().getName() == 'Opportunity'; } t2 = Limits.getCPUTime(); System.debug((t2-t1) + 'cpu units'); System.debug(Decimal.valueOf(t2-t1)/iterations + ' cpu time per evaluation'); // A slightly improved version of the check t1 = Limits.getCPUTime(); for(Integer i = 0; i < iterations; i++) { Boolean b = evt.WhatId?.getSObjectType() == Opportunity.SObjectType; } t2 = Limits.getCPUTime(); System.debug((t2-t1) + 'cpu units'); System.debug(Decimal.valueOf(t2-t1)/iterations + ' cpu time per evaluation');
Running that multiple times (to warm up any caches that Salesforce is using)...
| run | basic loop | getDescribe().getName() | getSObjectType() == Opportunity.SObjectType |
| 1 | 7 | 165 | 127 |
| 2 | 7 | 162 | 124 |
| 3 | 12 | 243 | 204 |
| 4 | 7 | 160 | 130 |
| 5 | 10 | 178 | 137 |
over 10k iterations, the "improved" solution runs about 30-40 CPU time less than the .getDescribe().getName() version of the check.
Just do whatever is consistent with the rest of your codebase and/or whatever is easier to read or takes less typing.
String.valueOf(anEvent.WhatId).startsWith('006') uses about 70 CPU time over 10k iterations. If you put that check into another method though, the CPU time used shoots up to be about 110-120.
So I take that to mean that the majority of the CPU time used is just in the overhead associated with calling/returning from methods.