2 USING: help.markup help.syntax words quotations sequences kernel ;
4 ARTICLE: "hints" "Compiler specialization hints"
5 "Specialization hints help the compiler generate efficient code."
7 "Specialization hints can help words which call a lot of generic words on the same object - perhaps in a loop - and in most cases, it is anticipated that this object is of a certain class, or even " { $link eq? } " to some literal. Using specialization hints, the compiler can be instructed to compile a branch at the beginning of the word; if the branch is taken, the input object has the assumed class or value, and inlining of generic methods can take place."
9 "Specialization hints are not declarations; if the inputs do not match what is specified, the word will still run, possibly slower if the compiled code cannot inline methods because of insufficient static type information."
11 "In some cases, specialization will not help at all, and can make generated code slower from the increase in code size. The compiler is capable of inferring enough static type information to generate efficient code in many cases without explicit help from the programmer. Specializers should be used as a last resort, after profiling shows that a critical loop makes a lot of repeated calls to generic words which dispatch on the same class."
13 "Type hints are declared with a parsing word:"
14 { $subsection POSTPONE: HINTS: }
15 "The specialized version of a word which will be compiled by the compiler can be inspected:"
16 { $subsection specialized-def } ;
19 { $values { "word" word } { "quot" quotation } }
20 { $description "Outputs the definition of a word after it has been split into specialized branches. This is the definition which will actually be compiled by the compiler." } ;
23 { $values { "defspec" "a definition specifier" } { "hints..." "a list of sequences of classes or literals" } }
24 { $description "Defines specialization hints for a word or a method."
26 "Each sequence in the list will cause a specialized version of the word to be compiled. Classes are tested for using their predicate, and literals are tested using " { $link eq? } "." }
27 { $examples "The " { $link append } " word has a specializer for the very common case where two strings or two arrays are appended:"
28 { $code "HINTS: append { string string } { array array } ;" }
29 "Specializers can also be defined on methods:"
31 "GENERIC: count-occurrences ( elt obj -- n )"
33 "M: sequence count-occurrences [ = ] with count ;"
35 "M: assoc count-occurrences"
36 " swap [ = nip ] curry assoc-filter assoc-size ;"
38 "HINTS: { sequence count-occurrences } { object array } ;"
39 "HINTS: { assoc count-occurrences } { object hashtable } ;"