Skip to content

Commit 43ced35

Browse files
StephenVavasisfredrikekre
authored andcommitted
more about type annotation (#23180)
* more about type annotation Type annotation not recommended for types constructed at run-time
1 parent fc54dc4 commit 43ced35

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

doc/src/manual/performance-tips.md

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -485,6 +485,34 @@ annotation in this context in order to achieve type stability. This is because t
485485
cannot deduce the type of the return value of a function, even `convert`, unless the types of
486486
all the function's arguments are known.
487487

488+
Type annotation will not enhance (and can actually hinder) performance if the type is constructed
489+
at run-time. This is because the compiler cannot use the annotation to specialize the subsequent
490+
code, and the type-check itself takes time. For example, in the code:
491+
492+
```julia
493+
function nr(a, prec)
494+
ctype = prec == 32 ? Float32 : Float64
495+
b = Complex{ctype}(a)
496+
c = (b + 1.0f0)::Complex{ctype}
497+
abs(c)
498+
end
499+
```
500+
501+
the annotation of `c` harms performance. To write performant code involving types constructed at
502+
run-time, use the [function-barrier technique](@ref kernal-functions) discussed below, and ensure
503+
that the constructed type appears among the argument types of the kernel function so that the kernel
504+
operations are properly specialized by the compiler. For example, in the above snippet, as soon as
505+
`b` is constructed, it can be passed to another function `k`, the kernel. If, for example, function
506+
`k` declares `b` as an argument of type `Complex{T}`, where `T` is a type parameter, then a type annotation
507+
appearing in an assignment statement within `k` of the form:
508+
509+
```julia
510+
c = (b + 1.0f0)::Complex{T}
511+
```
512+
513+
does not hinder performance (but does not help either) since the compiler can determine the type of `c`
514+
at the time `k` is compiled.
515+
488516
### Declare types of keyword arguments
489517

490518
Keyword arguments can have declared types:

0 commit comments

Comments
 (0)