I was wondering what the process of matching function arguments arguments against different function definitions actually looks like for Mathematica.
(Just to be clear, I'm not simply looking for an answer to the question "given two or more definitions for a head f, which will Mathematica choose?"—I'm interested in how the process itself takes place.)
So, for example, if I define a function f[x : _Integer] := 3, and then evaluate f[5] // Trace or f[5] // TracePrint, I never see Mathematica attempt to MatchQ 5 against _Integer. Likewise for any pattern.
For what I'm guessing might be related reasons, I can't define
ClearAll[f];
f[x : patt] := 3;
patt = _Integer;
in that order, and have it behave as I'd expect; the result of f[5] is then just f[5].
One exception seems to be patterns that involve function applications, e.g. _?g. Then g will show up in Trace. This makes me suspect that Mathematica does some sort of optimization when it can, and that the pattern matching typically takes place outside of the typical evaluation process...somehow.
(Note: I seem to remember seeing something at some point about a dispatch table being generated, so this might be a duplicate question, but I can't seem to find where. But even in that case, if it works like Dispatch, I don't quite understand the specifics of when it's applied, or how exactly the hash codes are used...)
This question is motivated by the following concern:
If I have something like Table[f[i], {i,n}], will i be matched against the definitions for f each time f is evaluated? Or does Mathematica "figure out" that i will be an integer each time f is called on it, and "plan" to use the _Integer definition of f (if it exists)? The latter seems unlikely to me, especially given the difference in the following:
ClearAll[f,g]
f[x_Integer] := Null
f[x_String] := Null
f[x : {_Integer, _Integer}] := Null
g[x_] := Null
RepeatedTiming[Do[f[{i, i}];, {i, 2000000}]]
(* {1.58606, Null} *)
RepeatedTiming[Do[g[{i, i}];, {i, 2000000}]]
(* {1.06015, Null} *)
I asked this question based on this concern, but realized I should get a better understanding of what's actually going on first!