Why does specifying the size of a class property slow down writes?
Mostrar comentarios más antiguos
I am trying to buffer some data in an object, and I noticed that specifying the size of the buffer in the class property affects the runtime performance. It doesn't make a lot of sense to me why performance would improve when the size of the data is not specified. I am running Matlab 2024b.
Here is a small example that illustrates how specifying the data size slows down the runtime performance by a factor of 5-10x. The array buffering is used to baseline the test.
classdef MyBufferFast < handle
properties
% No size property set.
buffer
end
methods
function [obj] = MyBufferFast()
obj.buffer = zeros(10, 1);
end
function [] = BufferData(obj, data)
% Slicing here to replicate middle-of-buffer insertion.
obj.buffer(1:10) = data;
end
end
end
classdef MyBufferSlow < handle
properties
% Why does setting the size property here slow it down?
buffer(10, 1) double
end
methods
function [obj] = MyBufferSlow()
obj.buffer = zeros(10, 1);
end
function [] = BufferData(obj, data)
% Slicing here to replicate middle-of-buffer insertion.
obj.buffer(1:10) = data;
end
end
end
%% Setup
clc; clear all; close all;
rng(1);
num_data = 100000;
data_to_buffer = randn(10, num_data);
%% Buffer with array
array_buffer = zeros(10, 1);
tic;
for idx = 1:num_data
array_buffer(1:10) = data_to_buffer(:, idx);
end
array_time = toc;
%% Buffer with fast object
my_buffer_fast = MyBufferFast();
tic;
for idx = 1:num_data
my_buffer_fast.BufferData(data_to_buffer(:, idx));
end
fast_buffer_time = toc;
%% Buffer with slow object
my_buffer_slow = MyBufferSlow();
tic;
for idx = 1:num_data
my_buffer_slow.BufferData(data_to_buffer(:, idx));
end
slow_buffer_time = toc;
%% Report
disp(array_time);
disp(fast_buffer_time);
disp(slow_buffer_time);
% Times
% array_time: 0.0546
% fast_buffer_time: 0.0806
% slow_buffer_time: 0.5379
Respuesta aceptada
Más respuestas (0)
Categorías
Más información sobre Programming Utilities en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!