在 Common Lisp 中是否有任何方法可以分配扁平结构数组 (AOS) 以提高效率?
我的意思是下面的 C 等价物。
typedef struct {
int x;
float y;
double z;
} foo_t;
#define SIZE 1000000
void bar()
{
foo_t *f = malloc( sizeof( foo_t ) * SIZE );
do_something_with( f );
}
通常在 Common Lisp 中,引用结构对象的指针数组用于表示这样的数据结构。
(defstruct foo
(x 0 :type fixnum)
(y 0.0 :type single-float)
(z 0d0 :type double-float))
(let* ((size 1000000)
(f (make-array size :element-type 'foo
:initial-contents (loop repeat size
collect (make-foo)))))
(do-something-with f))
当结构只有一种类型时,可以使用简单数组以命令方式获得非常高效的性能,尽管简单数组只接受一种类型作为其元素类型。
; (defstruct vertex
; (x 0d0 :type double-float)
; (y 0d0 :type double-float)
; (z 0d0 :type double-float))
(defun make-vertex-array (n)
(make-array n :element-type 'double-float :initial-element 0d0))
(defmacro vertex-x (ary i)
`(aref ,ary (+ (* ,i 3) 0)))
(defmacro vertex-y (ary i)
`(aref ,ary (+ (* ,i 3) 1)))
(defmacro vertex-z (ary i)
`(aref ,ary (+ (* ,i 3) 2)))
(let* ((size 1000000)
(ary (make-vertex-array 100))
(do-something-with ary))
我想听听关于如何处理具有多种元素类型的结构。
最佳答案
标准 Common Lisp 不提供这样的功能。我不知道实现高效结构数组的实现,其中结构在数组中分配。实现可能为某些结构实现高效的内存分配,但通常不会为结构向量实现。
这会给垃圾收集器带来挑战。当没有对它的实时引用时,通常一个对象是垃圾。如果我们允许在数组内部分配结构,那么如果没有对它的引用并且没有对它的引用(对数组内部的任何结构),该数组将是垃圾。
可能有提供类似功能的库 ( http://cliki.net/data%20formats )。
通常有 FFI(外部函数接口(interface))功能可以处理记录数组,或者可以使用 FFI 构建它们。
关于arrays - 有什么方法可以在 Common Lisp 中将扁平结构数组分配为 C?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29008545/