common lisp - defclass type information for performance -


in following program, removing line

    (declare (type (simple-array bit) arr)) 

makes running time increase more factor of 3, using sbcl. type information given in defclass macro via :type on other hand appears have no impact on performance.

(defclass class-1 () ((arr :type (simple-array bit))))  (defun sample (inst)   (declare (type class-1 inst))   (let ((arr (slot-value inst 'arr)))     (declare (type (simple-array bit) arr)) ;; 3x running time without     (map-into arr #'(lambda (dummy) (if (< (random 1.0) 0.5) 0 1)) arr)))  (let ((inst (make-instance 'class-1)))   (setf (slot-value inst 'arr) (make-array 10000 :element-type 'bit))   (loop 1 10000 (sample inst))) 

how can have same performance benefit without having declare arr slot simple-array bit each time use it? latter particularly annoying since (as far have found out) requires introduce binding via let or similar each time; cannot write (slot-value inst 'arr) in place need it.

first of all, sbcl-specific question, might better answer on sbcl user list. different compilers different optimizations, , ignore @ least declarations.

second, should let-bind arr because using twice.

third, can use the if want avoid let-bind:

(the (simple-array bit) (slot-value inst 'arr)) 

fourth, if want compiler infer type, use specific reader instead of slot-value:

(defclass c () ((arr :type (simple-array bit) :reader c-arr)))  (defun sample (inst)   (declare (type class-1 inst))   (let ((arr (c-arr inst)))     (map-into arr #'(lambda (dummy) (random 2)) arr))) 

c-arr should allow compiler infer value type easier, (as have discovered yourself!) might need declare return type:

(declaim (ftype (function (c) (simple-array bit)) c-arr)) 

the reason is, apparently, sbcl ignores slot type declarations.


Comments

Popular posts from this blog

windows - Single EXE to Install Python Standalone Executable for Easy Distribution -

c# - Access objects in UserControl from MainWindow in WPF -

javascript - How to name a jQuery function to make a browser's back button work? -