The fastest way to change structure

I have two different implementations right now on how to change the basic structure of a workspace from within a function.

To declare my structure in the base workspace:

arg = struct('aa', struct('abc',30));

The first function I tested uses the command evalin:

function modifyArg1(parameter, value)
    evalin('base', [parameter '=' value ';'])
end

And called like this:

modifyArg1('arg.aa.abc', '60')

The second function has the structure of argboth input and output:

function [arg] = modifyArg2(arg, parameter1, parameter2, value)
    arg.(parameter1).(parameter2) = value;
end

And called like this:

[arg] = modifyArg2(arg, 'aa', 'abc', 60);

I tested both functions to find out which one is the fastest:

tic
for ii = 1 : 10000
    [arg] = modifyArg2(arg, 'aa', 'abc', 60);
end
toc
tic
for ii = 1 : 10000
    modifyArgIn1('arg.aa.abc', '60');
end
toc
Elapsed time is 0.141994 seconds.
Elapsed time is 0.677188 seconds.

Therefore, the second function is almost 5 times faster. Is there any other way to do this faster?

+4
source share
1 answer

modifyArg2, . , , arg.(parameter1).(parameter2) = value;, , modifyArg2. , arg.(parameter1).(parameter2) = value; inline . :

parameter1 = 'aa';
parameter2 = 'abc';
tic
for ii = 1 : 10000   
    arg.(parameter1).(parameter2) = 60;     
end
toc

10 , modifyArg2. , modifyArg2 ( ):

tic
for ii = 1 : 10000   
    parameter1 = 'aa';
    parameter2 = 'abc';
    arg.(parameter1).(parameter2) = 60;     
end
toc
+1

Source: https://habr.com/ru/post/1526776/


All Articles