No, I don’t think it will.
Julia can’t use the type constraints on called functions,
to help the type inference system (except maybe as a heuristic).
This is incontrast to say F# (and probably many other languages, but F# is one I know can do this)
I don’t think it can do it,
because calling a function that doesn’t have a method isn’t illegal julia code,
it is just code that will through a MethodError
.
You can write code that depends on MethodError
s being thrown,
and catching them,
(and indeed for some really dynamic code, I have done that. Though I wouldn’t recommend.)
Anyway,
The following shows that it doesn’t change things much.
Notice the same allocations for the first call of f1
and f2
julia> f1(x::Int) = 3
f1 (generic function with 1 method)
julia> @time f1(1)
0.000158 seconds (381 allocations: 25.891 KiB)
3
julia> @time f1(1)
0.000003 seconds (4 allocations: 160 bytes)
3
julia> f2(x) = 3
f2 (generic function with 1 method)
julia> @time f2(1)
0.000193 seconds (381 allocations: 25.891 KiB)
3
Some rigor
Can collect data on this using
julia> function makeandtime_free()
fname = Base.gensym()
fval = rand()
@eval $fname(x) = $fval
@eval(@elapsed $fname(1))
end
makeandtime_free (generic function with 1 method)
julia> function makeandtime_constrained()
fname = Base.gensym()
fval = rand()
@eval $fname(x::Int) = $fval
@eval(@elapsed $fname(1))
end
makeandtime_constrained (generic function with 1 method)
Call that in a map
and then one then has a bunch of data.
Now hypothesis testing can find out if there is a statistically significant difference between the two.
I am not a statistician.
But I think we want the Unequal Variance t-Test
Perform an unequal variance two-sample t-test of the null hypothesis that x
and y
come from distributions with equal means against the alternative hypothesis that the distributions have different means.
julia> using HypothesisTests
julia> constrained_times = map(x->makeandtime_constrained(), 1:1000);
julia> free_times = map(x->makeandtime_free(), 1:1000);
julia> UnequalVariance(constrained_times, free_times)
UnequalVarianceTTest UnequalVarianceZTest
julia> UnequalVarianceTTest(constrained_times, free_times)
Two sample t-test (unequal variance)
------------------------------------
Population details:
parameter of interest: Mean difference
value under h_0: 0
point estimate: -3.947500500000003e-5
95% confidence interval: (-0.0001, 0.0)
Test summary:
outcome with 95% confidence: fail to reject h_0
two-sided p-value: 0.1626
Details:
number of observations: [1000,1000]
t-statistic: -1.3969401508247017
degrees of freedom: 1928.9743996051652
empirical standard error: 2.8258193435628185e-5
So that says that we can not reject the null hypothesis.
So it is entirely reasonable that the constrained and the unconstrained function first run time (and thus inference time),
is on average the same.