November 2018
Intermediate to advanced
460 pages
14h 1m
English
A typically poor implementation of a function performing the summation is as follows:
julia> function possum2c(x) s = 0 for v in x s += ifelse(v > 0, v, 0) end s endpossum2c (generic function with 1 method)julia> @btime possum2c(x) 14.670 ms (1000001 allocations: 15.26 MiB)398244.60749279766
The difference between this and our preceding code is that we initiate the s variable using an Int value, and then ifelse(v > 0, v, 0) returns either a variable of the typeof(v) type or Int (which is of the 0 type). The problem is that in this case the Julia compiler is not able to determine the type of s uniquely (so, we say that s is not type stable). We can see that this significantly degrades code performance. In the Ensuring type ...
Read now
Unlock full access