From d77ed9f51217648ae29042576bdec4b6acd41a45 Mon Sep 17 00:00:00 2001 From: Kristoffer Carlsson Date: Wed, 17 Dec 2025 13:39:25 +0100 Subject: [PATCH] performance tips docs: add a note when force sepecialization of a function may be required with optional arguments --- doc/src/manual/performance-tips.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/doc/src/manual/performance-tips.md b/doc/src/manual/performance-tips.md index f821738d3b161..6d968891bd99e 100644 --- a/doc/src/manual/performance-tips.md +++ b/doc/src/manual/performance-tips.md @@ -652,6 +652,29 @@ would not normally specialize that method call. You need to check the when argument types are changed, i.e., if `Base.specializations(@which f(...))` contains specializations for the argument in question. +Note that in the presence of keywords and optional positional arguments, you may need to force specialization of a method argument +even though the method is called in the body. This is due to how Julia rewrites method with default arguments. If we consider: + +```julia +g(f, x=1) = f(...) +``` + +the method argument `f` is here clearly used within the method `g`. However, julia will rewrite this as: + +```julia +g(f, x) = f(...) +g(f) = g(f, 1) +``` + +With this rewrite, the second method that passes along the default argument value does no longer use `f`, calling `g(f)` may therefore not specialize on `f`. +Writing the original definition as + +```julia +g(f::F, x=1) where {F} = f(...) +``` + +woudld solve this. + ### Write "type-stable" functions When possible, it helps to ensure that a function always returns a value of the same type. Consider