Csound Csound-dev Csound-tekno Search About

[Csnd-dev] array pass by value / reference

Date2019-12-23 11:30
FromEduardo Moguillansky
Subject[Csnd-dev] array pass by value / reference

Using arrays in UDOs imposes a big overhead when compared to using tables because of the allocations and memory copying involved in passing arrays by value. To test the overhead I implemented a set of opcodes "ref" and "deref" which create a reference counted pointer to an array and allow to pass these by reference. An UDO implemented like this uses in my tests 0.25 of the time of the same UDO. In the following example, instr 1 takes 4 times longer than instr 2 when called repeatedly.

In order to implement such opcodes reliably it would be necessary to add a field to the ARRAYDAT struct to mark that the array owns its own memory. This would be false for the cases where the array is a reference to another array. Such change would allow other benefits, like an array being a view on other array (for instance, getrow could return such a view)

In case anyone wants to test this, these opcodes are documented here: https://csound-plugins.github.io/csound-plugins/opcodes/ref.html

cheers,
Eduardo

-------------------------

opcode arrayadd, i[], i[]i
  ; pass by value in and out
  iIn[], ix xin
  iOut[] = iIn + ix
  xout iOut
endop

opcode arrayadd_byref, 0, iii
  ; pass by ref in and out
  irefin, iadd, irefout xin
  iIn[]  deref irefin
  iOut[] deref irefout
endop

instr 1
  iIn[] genarray 0, 100000
  iOut[] = arrayadd(iIn, 0.5)
  turnoff
endin

instr 2
  iIn[] genarray 0, 100000
  iOut[] init lenarray(iIn)
  arrayadd_byref ref(iIn), 0.5, ref(iOut)
  turnoff
endin