在以下程序中,删除该行
(declare (type (simple-array bit) arr))
Run Code Online (Sandbox Code Playgroud)
使用SBCL使运行时间增加3倍以上.另一方面,defclass宏通过中给出的类型信息:type似乎对性能没有影响.
(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 for i from 1 to 10000 do (sample inst)))
Run Code Online (Sandbox Code Playgroud)
如何在不必每次使用时都声明arr插槽的情况下获得相同的性能优势simple-array bit?后者特别烦人,因为(据我所知) …
class A { public: int x[100]; };
Run Code Online (Sandbox Code Playgroud)
声明A a不会初始化对象(由字段中的垃圾值看到x).以下将触发初始化:A a{}或auto a = A()或auto a = A{}.
这三个中的任何一个应该是首选吗?
接下来,让我们使它成为另一个类的成员:
class B { public: A a; };
Run Code Online (Sandbox Code Playgroud)
默认构造函数B似乎负责初始化a.但是,如果使用自定义构造函数,我必须处理它.以下两个选项有效:
class B { public: A a; B() : a() { } };
Run Code Online (Sandbox Code Playgroud)
要么:
class B { public: A a{}; B() { } };
Run Code Online (Sandbox Code Playgroud)
这两个中的任何一个都应该是首选吗?