Avoid Updating Static Data
If only a small portion of the data defining a graphics scene changes with each update of the screen, you can improve performance by updating only the data that changes. The following example illustrates this technique.
Code with Poor Performance | Code with Better Performance |
---|---|
In this example, a marker moves along the surface by creating both objects with each pass through the loop. [sx,sy,sz] = peaks(500); nframes = 490; for t = 1:nframes surf(sx,sy,sz,'EdgeColor','none') hold on plot3(sx(t+10,t),sy(t,t+10),... sz(t+10,t+10)+0.5,'o',... 'MarkerFaceColor','red',... 'MarkerSize',14) hold off drawnow end | Create the surface, then update the [sx,sy,sz] = peaks(500); nframes = 490; surf(sx,sy,sz,'EdgeColor','none') hold on h = plot3(sx(1,1),sy(1,1),sz(1,1),'o',... 'MarkerFaceColor','red',... 'MarkerSize',14); hold off for t = 1:nframes set(h,'XData',sx(t+10,t),... 'YData',sy(t,t+10),... 'ZData',sz(t+10,t+10)+0.5) drawnow end |
Segmenting Data to Reduce Update Times
Consider the case where an object’s data grows very large while code executes in a loop, such as a line tracing a signal over time.
With each call to drawnow
, the updates
are passed to the renderer. The performance decreases as the data
arrays grow in size. If you are using this pattern, adopt the segmentation
approach described in the example on the right.
Code with Poor Performance | Code with Better Performance |
---|---|
% Grow data figure('Position',[10,10,1500,400]) n = 5000; h = stairs(1,1); ax = gca; ax.XLim = [1,n]; ax.YLim = [0,1]; ax.ZLim = [0,1]; ax.NextPlot = 'add'; xd = 1:n; yd = rand(1,n); tic for ix = 1:n set(h,'XData',xd(1:ix),'YData',yd(1:ix)); drawnow; end toc | % Segment data figure('Position',[10,10,1500,400]) n = 5000; seg_size = 500; xd = 1:n; yd = rand(1,n); h = stairs(1,1); ax = gca; ax.XLim = [1,n]; ax.YLim = [0,1]; ax.ZLim = [0,1]; ax.NextPlot = 'add'; tic start = 1; for ix=1:n % Limit object size if (ix-start > seg_size) start = ix-1; h = stairs(1,1); end set(h,'XData',xd(start:ix),... 'YData',yd(start:ix)); % Update display in 50 point chunks if mod(ix,50) == 0 drawnow; end end toc The performance of this code is better because the limiting factor is the amount of data sent during updates. |