Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any ways to allocate flattened array of structure as C in Common Lisp?

Are there any ways to allocate flattened array of structure (AOS) for efficiency in Common Lisp?

What I mean is the following C equivalent.

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 );
}

Usually in Common Lisp, array of pointers that refer structure objects are used to represent such a data structure.

(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))

When a structure has only a kind of type, simple arrays can be used to gain very efficient performance in imperative manner, although simple arrays accept only a kind of type as its element type.

; (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))

I want to hear about something to do like this with structures with several kinds of element types.

like image 336
masayuki takagi Avatar asked Sep 14 '25 03:09

masayuki takagi


1 Answers

Standard Common Lisp does not provide such a feature. I don't know of implementations which implement efficient arrays of structures, where the structures are allocated in the arrays. Implementations might implement efficient memory allocation for some structures, but usually not for vectors of structures.

It would provide a challenge to the garbage collector. Usually an object is garbage when there are no live references to it. If we would allow structures allocated inside arrays, the array would be garbage if there are no references to it AND no references into it (to any of the structures inside of the array).

There might be libraries which provide similar features ( http://cliki.net/data%20formats ).

There are usually FFI (foreign function interface) functionalities which can deal with arrays of records or one can build them using the FFI.

like image 89
Rainer Joswig Avatar answered Sep 17 '25 04:09

Rainer Joswig