var theFunction = condition ? "querySelector" : "getElementById";
...
document[theFunction](...)
it won't apply to if (condition)
document.querySelector(...)
else
document.getElementById(...)
As from the point of view of the runtime the latter has two call sites, and each one is monomorphic and will very quickly (first layer of the JIT tower generally) become a Structure/Shape/HiddenClass check on `document` followed by a direct call to the host environment's implementation function (or more likely the argument checking and marshaling function before the actual internal implementation).It is possible that the higher level JITs pay attention to the branch counts on conditions or use other side channels for the deopt, but for host functions it's generally not something that will happen as the JITs see natively implemented functions as largely opaque barriers - they only have a few internal (to the runtime itself) cases where they make any assumptions about the behaviour of host functions.
Also there's a performance cliff when you have a lot of unique ids (or selectors in use from JS).
When you hit the cache querySelector is primarily a getElementById call and then some overhead to match the selector a second time (which chrome should really optimize):
https://source.chromium.org/chromium/chromium/src/+/main:thi...
But if you have more than 256 selectors and ids in use:
https://source.chromium.org/chromium/chromium/src/+/main:thi...
You'll start to hit the selector parser a lot more and then querySelector will be a fair bit slower going through the CSS parser.
Many many years ago I recall querySelector starting out with a check for #someCSSIdentifier and shortcutting to the getElementById path, but maybe my memory is playing tricks on me.