1.0.39.9: improvements to the manual
[sbcl.git] / doc / manual / efficiency.texinfo
1 @node Efficiency
2 @comment  node-name,  next,  previous,  up
3 @chapter Efficiency
4 @cindex Efficiency
5
6 @menu
7 * Slot access::
8 * Dynamic-extent allocation::
9 * Modular arithmetic::
10 * Global and Always-Bound variables::
11 * Miscellaneous Efficiency Issues::
12 @end menu
13
14 @node  Slot access
15 @comment  node-name,  next,  previous,  up
16 @section Slot access
17 @cindex Slot access
18
19 @subsection Structure object slot access
20
21 Structure slot accessors are efficient only if the compiler is able to
22 open code them: compiling a call to a structure slot accessor before
23 the structure is defined, declaring one @code{notinline}, or passing
24 it as a functional argument to another function causes severe
25 perfomance degradation.
26
27 @subsection Standard object slot access
28
29 The most efficient way to access a slot of a @code{standard-object} is
30 by using @code{slot-value} with a constant slot name argument inside a
31 @code{defmethod} body, where the variable holding the instance is a
32 specializer parameter of the method and is never assigned to. The cost
33 is roughly 1.6 times that of an open coded structure slot accessor.
34
35 Second most efficient way is to use a CLOS slot accessor, or
36 @code{slot-value} with a constant slot name argument, but in
37 circumstances other than specified above. This may be up to 3 times as
38 slow as the method described above.
39
40 Example:
41
42 @lisp
43 (defclass foo () ((bar)))
44
45 ;; Fast: specializer and never assigned to
46 (defmethod quux ((foo foo) new)
47   (let ((old (slot-value foo 'bar)))
48     (setf (slot-value foo 'bar) new)
49     old))
50
51 ;; Slow: not a specializer
52 (defmethod quux ((foo foo) new)
53   (let* ((temp foo)
54          (old (slot-value temp 'bar)))
55     (setf (slot-value temp 'bar) new)
56     old))
57
58 ;; Slow: assignment to FOO
59 (defmethod quux ((foo foo) new)
60   (let ((old (slot-value foo 'bar)))
61     (setf (slot-value foo 'bar) new)
62     (setf foo new)
63     old))
64 @end lisp
65
66 Note that when profiling code such as this, the first few calls to the
67 generic function are not representative, as the dispatch mechanism is
68 lazily set up during those calls.
69
70 @node  Dynamic-extent allocation
71 @comment  node-name,  next,  previous,  up
72 @section Dynamic-extent allocation
73 @cindex @code{dynamic-extent} declaration
74 @cindex declaration, @code{dynamic-extent}
75
76 SBCL has limited support for performing allocation on the stack when a
77 variable is declared @code{dynamic-extent}. The @code{dynamic-extent}
78 declarations are not verified, but are simply trusted as long as
79 @code{sb-ext:*stack-allocate-dynamic-extent*} is true.
80
81 If dynamic extent constraints specified in the Common Lisp standard
82 are violated, the best that can happen is for the program to have
83 garbage in variables and return values; more commonly, the system will
84 crash.
85
86 @include var-sb-ext-star-stack-allocate-dynamic-extent-star.texinfo
87
88 There are many cases when @code{dynamic-extent} declarations could be
89 useful. At present, SBCL implements stack allocation for
90
91 @itemize
92
93 @item
94 @code{&rest} lists, when these are declared @code{dynamic-extent}.
95
96 @item
97 @findex @cl{cons}
98 @findex @cl{list}
99 @findex @cl{list*}
100 @findex @cl{vector}
101 @code{cons}, @code{list}, @code{list*}, and @code{vector} when the
102 result is bound to a variable declared @code{dynamic-extent}.
103
104 @item
105 @findex @cl{make-array}
106 simple forms of @code{make-array}, whose result is bound to a variable
107 declared @code{dynamic-extent}: stack allocation is possible only if
108 the resulting array is known to be both simple and one-dimensional,
109 and has a constant @code{:element-type}.
110
111 @cindex Safety optimization quality
112 @strong{Note}: stack space is limited, so allocation of a large vector
113 may cause stack overflow. For this reason potentially large vectors,
114 which might circumvent stack overflow detection, are stack allocated
115 only in zero @code{safety} policies.
116
117 @item
118 @findex @cl{flet}
119 @findex @cl{labels}
120 @cindex @code{safety} optimization quality
121 @cindex optimization quality, @code{safety}
122 closures defined with @code{flet} or @code{labels}, with a bound
123 @code{dynamic-extent} declaration. Closed-over variables, which are
124 assigned to (either inside or outside the closure) are still allocated
125 on the heap. Blocks and tags are also allocated on the heap, unless
126 all non-local control transfers to them are compiled with zero
127 @code{safety}.
128
129 @item
130 user-defined structures when the structure constructor defined using
131 @code{defstruct} has been declared @code{inline} and the result of the
132 call to the constructor is bound to a variable declared
133 @code{dynamic-extent}.
134
135 @strong{Note}: structures with ``raw'' slots can currently be
136 stack-allocated only on x86 and x86-64.
137
138 @item
139 all of the above when they appear as initial parts of another
140 stack-allocated object.
141
142 @end itemize
143
144 Examples:
145
146 @lisp
147 ;;; Declaiming a structure constructor inline before definition makes
148 ;;; stack allocation possible.
149 (declaim (inline make-thing))
150 (defstruct thing obj next)
151
152 ;;; Stack allocation of various objects bound to DYNAMIC-EXTENT
153 ;;; variables.
154 (let* ((list (list 1 2 3))
155        (nested (cons (list 1 2) (list* 3 4 (list 5))))
156        (vector (make-array 3 :element-type 'single-float))
157        (thing (make-thing :obj list
158                           :next (make-thing :obj (make-array 3)))))
159   (declare (dynamic-extent list nested vector thing))
160   ...)
161
162 ;;; Stack allocation of arguments to a local function is equivalent
163 ;;; to stack allocation of local variable values.
164 (flet ((f (x)
165          (declare (dynamic-extent x))
166          ...))
167   ...
168   (f (list 1 2 3))
169   (f (cons (cons 1 2) (cons 3 4)))
170   ...)
171
172 ;;; Stack allocation of &REST lists
173 (defun foo (&rest args)
174   (declare (dynamic-extent args))
175   ...)
176 @end lisp
177
178 Future plans include
179
180 @itemize
181
182 @item
183 Stack allocation of assigned-to closed-over variables, where these are
184 declared @code{dynamic-extent};
185
186 @item
187 Automatic detection of the common idiom of applying a function to some
188 defaults and a @code{&rest} list, even when this is not declared
189 @code{dynamic-extent};
190
191 @item
192 Automatic detection of the common idiom of calling quantifiers with a
193 closure, even when the closure is not declared @code{dynamic-extent}.
194
195 @end itemize
196
197 @node  Modular arithmetic
198 @comment  node-name,  next,  previous,  up
199 @section Modular arithmetic
200 @cindex Modular arithmetic
201 @cindex Arithmetic, modular
202 @cindex Arithmetic, hardware
203 @findex @cl{logand}
204 Some numeric functions have a property: @var{N} lower bits of the
205 result depend only on @var{N} lower bits of (all or some)
206 arguments. If the compiler sees an expression of form @code{(logand
207 @var{exp} @var{mask})}, where @var{exp} is a tree of such ``good''
208 functions and @var{mask} is known to be of type @code{(unsigned-byte
209 @var{w})}, where @var{w} is a ``good'' width, all intermediate results
210 will be cut to @var{w} bits (but it is not done for variables and
211 constants!). This often results in an ability to use simple machine
212 instructions for the functions.
213
214 Consider an example.
215
216 @lisp
217 (defun i (x y)
218   (declare (type (unsigned-byte 32) x y))
219   (ldb (byte 32 0) (logxor x (lognot y))))
220 @end lisp
221
222 The result of @code{(lognot y)} will be negative and of type
223 @code{(signed-byte 33)}, so a naive implementation on a 32-bit
224 platform is unable to use 32-bit arithmetic here. But modular
225 arithmetic optimizer is able to do it: because the result is cut down
226 to 32 bits, the compiler will replace @code{logxor} and @code{lognot}
227 with versions cutting results to 32 bits, and because terminals
228 (here---expressions @code{x} and @code{y}) are also of type
229 @code{(unsigned-byte 32)}, 32-bit machine arithmetic can be used.
230
231 As of SBCL 0.8.5 ``good'' functions are @code{+}, @code{-};
232 @code{logand}, @code{logior}, @code{logxor}, @code{lognot} and their
233 combinations; and @code{ash} with the positive second
234 argument. ``Good'' widths are 32 on HPPA, MIPS, PPC, Sparc and x86 and
235 64 on Alpha.  While it is possible to support smaller widths as well,
236 currently this is not implemented.
237
238 @node  Global and Always-Bound variables
239 @comment  node-name,  next,  previous,  up
240 @section Global and Always-Bound variables
241
242 @include macro-sb-ext-defglobal.texinfo
243
244 @deffn {Declaration} @sbext{global}
245
246 Syntax: @code{(sb-ext:global symbol*)}
247
248 Only valid as a global proclamation.
249
250 Specifies that the named symbols cannot be proclaimed or locally
251 declared @code{special}. Proclaiming an already special or constant
252 variable name as @code{global} signal an error. Allows more efficient
253 value lookup in threaded environments in addition to expressing
254 programmer intention.
255 @end deffn
256
257 @deffn {Declaration} @sbext{always-bound}
258
259 Syntax: @code{(sb-ext:always-bound symbol*)}
260
261 Only valid as a global proclamation.
262
263 Specifies that the named symbols is always bound. Inhibits @code{makunbound}
264 of the named symbols. Proclaiming an unbound symbol as @code{always-bound} signals
265 an error. Allows compiler to elide boundness checks from value lookups.
266 @end deffn
267
268 @node  Miscellaneous Efficiency Issues
269 @comment  node-name,  next,  previous,  up
270 @section Miscellaneous Efficiency Issues
271
272 FIXME: The material in the CMUCL manual about getting good
273 performance from the compiler should be reviewed, reformatted in
274 Texinfo, lightly edited for SBCL, and substituted into this
275 manual. In the meantime, the original CMUCL manual is still 95+%
276 correct for the SBCL version of the Python compiler. See the
277 sections
278
279 @itemize
280 @item Advanced Compiler Use and Efficiency Hints
281 @item Advanced Compiler Introduction
282 @item More About Types in Python
283 @item Type Inference
284 @item Source Optimization
285 @item Tail Recursion
286 @item Local Call
287 @item Block Compilation
288 @item Inline Expansion
289 @item Object Representation
290 @item Numbers
291 @item General Efficiency Hints
292 @item Efficiency Notes
293 @end itemize
294
295 Besides this information from the CMUCL manual, there are a few other
296 points to keep in mind.
297
298 @itemize
299
300 @item
301 @findex @cl{let}
302 @findex @cl{let*}
303 @findex @cl{setq}
304 @findex @cl{setf}
305 The CMUCL manual doesn't seem to state it explicitly, but Python has a
306 mental block about type inference when assignment is involved. Python
307 is very aggressive and clever about inferring the types of values
308 bound with @code{let}, @code{let*}, inline function call, and so
309 forth. However, it's much more passive and dumb about inferring the
310 types of values assigned with @code{setq}, @code{setf}, and
311 friends. It would be nice to fix this, but in the meantime don't
312 expect that just because it's very smart about types in most respects
313 it will be smart about types involved in assignments.  (This doesn't
314 affect its ability to benefit from explicit type declarations
315 involving the assigned variables, only its ability to get by without
316 explicit type declarations.)
317
318 @c <!-- FIXME: Python dislikes assignments, but not in type
319 @c     inference. The real problems are loop induction, closed over
320 @c     variables and aliases. -->
321
322 @item
323 Since the time the CMUCL manual was written, CMUCL (and thus SBCL) has
324 gotten a generational garbage collector. This means that there are
325 some efficiency implications of various patterns of memory usage which
326 aren't discussed in the CMUCL manual. (Some new material should be
327 written about this.)
328
329 @item
330 SBCL has some important known efficiency problems.  Perhaps the most
331 important are
332
333 @itemize @minus
334
335 @item
336 The garbage collector is not particularly efficient, at least on
337 platforms without the generational collector (as of SBCL 0.8.9, all
338 except x86).
339
340 @item
341 Various aspects of the PCL implementation of CLOS are more inefficient
342 than necessary.
343
344 @end itemize
345
346 @end itemize
347
348 Finally, note that Common Lisp defines many constructs which, in
349 the infamous phrase, ``could be compiled efficiently by a
350 sufficiently smart compiler''. The phrase is infamous because
351 making a compiler which actually is sufficiently smart to find all
352 these optimizations systematically is well beyond the state of the art
353 of current compiler technology. Instead, they're optimized on a
354 case-by-case basis by hand-written code, or not optimized at all if
355 the appropriate case hasn't been hand-coded. Some cases where no such
356 hand-coding has been done as of SBCL version 0.6.3 include
357
358 @itemize
359
360 @item
361 @code{(reduce #'f x)} where the type of @code{x} is known at compile
362 time
363
364 @item
365 various bit vector operations, e.g.  @code{(position 0
366 some-bit-vector)}
367
368 @item
369 specialized sequence idioms, e.g.  @code{(remove item list :count 1)}
370
371 @item
372 cases where local compilation policy does not require excessive type
373 checking, e.g.  @code{(locally (declare (safety 1)) (assoc item
374 list))} (which currently performs safe @code{endp} checking internal
375 to assoc).
376
377 @end itemize
378
379 If your system's performance is suffering because of some construct
380 which could in principle be compiled efficiently, but which the SBCL
381 compiler can't in practice compile efficiently, consider writing a
382 patch to the compiler and submitting it for inclusion in the main
383 sources. Such code is often reasonably straightforward to write;
384 search the sources for the string ``@code{deftransform}'' to find many
385 examples (some straightforward, some less so).