Skip to content

Instantly share code, notes, and snippets.

@ProjectEli
Created May 19, 2021 02:16
Show Gist options
  • Save ProjectEli/7423ef2ad963abb11e7257ea711e7c59 to your computer and use it in GitHub Desktop.
Save ProjectEli/7423ef2ad963abb11e7257ea711e7c59 to your computer and use it in GitHub Desktop.
Check lazy copy behavior of struct in MATLAB
% ref: https://kr.mathworks.com/matlabcentral/answers/719-declaring-many-variables-from-work-space-into-function-workspace
%% Init
close all; clear; clc; disp(mfilename);
N=5;
%% Main
S = struct;
S.increment = 1;
S.x = 0;
S = allocatelargevariable(S);
%% increase var inside S without re-assigning
for k = 1:N
disp(k);
S = increasevar(S);
end
%% increase var inside S with label change
for k = 1:N
disp(k);
S = increasevarwithlabelchange(S);
end
%% increase var inside S with re-assigning
for k = 1:N
disp(k);
S = increasevarwithreassign(S);
end
%% increase var inside S with explicit assigning
for k = 1:N
disp(k);
S = increasevarwithexplicitassign(S);
end
%% function definitions
function [S] = allocatelargevariable(S)
%allocateLargevariable Allocate large variable in struct S
S.largevariable = rand(20000);
end
function [S] = increasevar(S)
S.x = S.x + S.increment;
end
function [output] = increasevarwithlabelchange(S)
S.x = S.x + S.increment;
output=S;
end
function [S2] = increasevarwithreassign(S)
S2 = S;
S2.x = S.x + S.increment;
end
function [S2] = increasevarwithexplicitassign(S)
S2 = S;
S2 = allocatelargevariable(S2);
S2.x = S.x + S.increment;
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment