Assignment by Reference

DolphinDB uses "&" to indicate assignment by reference. In contrast with assignment by value, assignment by reference does not make a new copy of the original value, but points to the original value.

The main benefit of reference assignment is to avoid unnecessary object copying, especially when the object is very large.

Syntax

&<variable>=<object>

Examples

y=6 4 7;
y;
// output
[6,4,7]

&x=y;
x;
// output
[6,4,7]

// modify y
y[1]=0;
y;
// output
[6,0,7]
// modifying the value of y also modifies the value of x
x;
// output
[6,0,7]

// modify x
x[0]=3;
x;
// output
[3,0,7]
// modifying the value of x also modifies the value of y
y;
// output
[3,0,7]

y=1..3;
&x=y;
y=6..4;
x;
// output
[1,2,3]
// if y is assigned another vector, x is not affected

The example below shows data swap using reference is much more efficient than using assignment by value

n=20000000;
// generate 2 double vectors with 20 million elements
x=rand(200000.0, n);
y=rand(200000.0, n);

// data swap using assignment by value
timer {t=x;x=y;y=t};
// output
Time elapsed: 292.005 ms

// data swap using assignment by reference
timer {&t=x;&x=y;&y=t};
// output
Time elapsed: 0 ms