lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hi Everyone,
I am in a process of creating Lua bindings to some numerical C/C++
libraries with rich matrix API. In modern day numeric software it is
fashionable to use algebraic notations for math operations for the
sake of readability of mathematical expressions. Unfortunately, these
algebraic notations, being indeed readable and familiar, could cause
mayhem by means of producing numerous temporary objects depleting
memory resources and taxing CPU. Let me give an example to illustrate

Let say: m, m1 and m2 are  square NxN matrices. In the following for-loop

for n=1,1000 do
    m= m*m1 + m2
end

on each iteration one temporary matrix is created to store the result
of matrix multiplication "*". It is used only once as an
input-variable to "+" which in turn allocates another matrix which is
then bound to m. The previous value of m as well the temporary object
are now unreferenced and eligible for garbage collection. As a result,
performance suffers first from excessive "malloc" overhead allocation
matrices on each iteration and, secondly, from GC overhead if GC is
actively reclaiming all those "use once" temporary objects.

In the older days of numerics from 60-es to 80-es this problem was
easily resolved by shifting *all* resource management to a user.
Matrix APIs simply were not allocating or freeing the resources. A
user was supposed to pass a reference or pointer to pre-allocated
matrix to hold the result. Such a design solved the problem at the
expense of readability. Now you cannot copy/paste math expressions
from text-books into the code anymore.

Modern and successful systems such as Matlab (not very modern after
all) or Mathematica do retain math-formula like algebraic notations
and hopefully do some proprietary stuff to eliminate/reuse
temporaries.

Is it possible to do something in Lua and somehow control use of
temporary objects when dealing with typical +-*/ math operations in
Lua?? The underlying math library API is of the older variety and
expects user to do all the resource allocations.

Any hint is appreciated!

--Leo--