@@ -485,6 +485,34 @@ annotation in this context in order to achieve type stability. This is because t
485
485
cannot deduce the type of the return value of a function, even ` convert ` , unless the types of
486
486
all the function's arguments are known.
487
487
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
+
488
516
### Declare types of keyword arguments
489
517
490
518
Keyword arguments can have declared types:
0 commit comments