efficiency using struct.field vs variable
4 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Ricky
el 16 de Nov. de 2017
Hi, I am curious about the efficiency of using structure.field vs variable in function but I don't know how to search such particular question.
Basically I need to use a variable inside a function so I use structure to pass the information. Then inside the function, the variable will be used multiple times. So I can have two approaches. Every time I need the variable, I can either assign it to a variable at the start of the function, or use it from the structure. Two approaches in code provided below:
output=myfunction(mystruct)
Method 1:
myvariable=mystruct.myfield;
myvariable=myvariable*5/10+3...
Method 2:
mystruct.myfield=mystruct.myfield*5/10+3...
Not sure which one is faster if I got loads of use. Hope my question is clear.
Regards,
Ricky
0 comentarios
Respuesta aceptada
Walter Roberson
el 16 de Nov. de 2017
In the small timing test I just did, leaving the value inside the struct was slightly faster. However, it is entirely possible that I simply did not do enough calculation with the variable to make up for the cost of doing the assignment to the variable.
Basically... you should time both versions.
Be careful, though: I have multiple times found that if I use something like
result1 = timeit(first_test,0)
result2 = timeit(second_test,0)
that first test I do is notably slower, so exchanging first_test and second_test would give very different results about which was faster. It is not just the first timeit() call either: if I use a loop to call timeit repeatedly then the results for the entire first loop are odd.
str = struct('foo', rand(1,50), 'bar', 'hello there how are you?');
F1 = @() fun_direct_struct(str);
F2 = @() fun_tovar(str);
N = 100;
T1a = zeros(1, N);
T1b = zeros(1, N);
T2a = zeros(1, N);
for K = 1 : N
T1a(K) = timeit(F1, 0);
end
for K = 1 : N
T2a = timeit(F2, 0);
end
for K = 1 : N
T1b = timeit(F1, 0);
end
plot(1:N, T1a, 'k*-', 1:N, T1b, 'kv--', 1:N, T2a, 'b.:')
legend({'T1a', 'T1b', 'T2a'});
In the above, T1b and T2a are pretty much constant in the time they take each iteration, but T1a varies a lot, especially initially. If you were to only measure F1 the first time then you would get a very different impression about which function was slower.
Más respuestas (0)
Ver también
Categorías
Más información sobre Scope Variables and Generate Names en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!