Essays/In-Place Operations

From J Wiki
Jump to navigation Jump to search

This Essay applies to J versions before Version 8.04. Versions 8.05 and later support in-place operations more generally

There are three "in-place" operations for the "direct" datatypes:

xyz=: aa i} xyz
xyz=: aa (i}) xyz
xyz=: xyz i}~ aa    NB. J6.03 or later

xyz=: xyz,aa

xyz=: b}xyz,:y   NB. b must be Boolean
xyz=: b}y,:xyz

=. instead of =: also works; aa or i may be parenthesized. Boxed, extended integer, and rationals are indirect datatypes; other datatypes are direct.

In-place means that an existing array is modified as opposed to creating a new array, resulting in large savings in time and space. The following examples illustrate the point:

   xyz=: 1e6 ?@$ 2e9
   i=: 100 ?@$ # xyz
   aa=: ($i) ?@$ 1e3

   ts=: 6!:2 , 7!:2@]  NB. time and space

   ts 'xyz=: aa i} xyz'        NB. in-place
2.12317e_5 1600
   ts 'xyz=: aa i} (xyz)'      NB. not in-place
0.0117526 4.19597e6
   ts 'aa i}xyz'               NB. not in-place
0.0112489 4.19571e6

   pqr=: 1e6 ?@$ 2e9
   b=: ($xyz) ?@$ 2

   (b}xyz,:pqr) -: (xyz*-.b)+pqr*b
1

   ts 'xyz=: b}xyz,:pqr'       NB. in-place
0.0170625 1280
   ts 'b}xyz,:pqr'             NB. not in-place
0.0693116 2.09725e7
   ts 'xyz=: (xyz*-.b)+pqr*b'  NB. not in-place
0.0245808 1.36326e7

The patterns are very specific and are recognized at word formation time. Therefore, the patterns accommodate variations immaterial with respect to word formation (such as non-essential spaces), but are thwarted by syntactic variations (such as in the second benchmark above, with the extra parens).

In-place operations impose a small cost on all sentences, even those that have nothing to do with in-place operations, because it takes time to detect (or reject) the patterns. For explicit definitions, that cost is paid just once at the time of definition.



Contributed by Roger Hui.