This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English version of the page.

Note: This page has been translated by MathWorks. Click here to see
To view all translated materials including this page, select Country from the country navigator on the bottom of this page.

Judicious Object Creation

Object Overhead

Graphics objects are complex structures that store information (data and object characteristics), listen for certain events to occur (callback properties), and can cause changes to other objects to accommodate their existence (update to axes limits, and so on). Therefore, creating an object consumes resources.

When performance becomes an important consideration, try to realize your objectives in a way that consumes a minimum amount of resources.

You can often improve performance by following these guidelines:

  • Do not create unnecessary objects

  • Avoid searching the object hierarchy

Do Not Create Unnecessary Objects

Look for cases where you can create fewer objects and achieve the same results. For example, suppose you want to plot a 10-by-1000 array of points showing only markers.

This code creates 1000 line objects:

x = rand(10,1000);
y = rand(10,1000);
plot(x,y,'LineStyle','none','Marker','.','Color','b');

Convert the data from 10-by-1000 to 10000-by-1. This code creates a graph that looks the same, but creates only one object:

plot(x(:),y(:),'LineStyle','none','Marker','.','Color','b')

Use NaNs to Simulate Multiple Lines

If coordinate data contains NaNs, MATLAB® does not render those points. You can add NaNs to vertex data to create line segments that look like separate lines. Place the NaNs at the same element locations in each vector of data. For example, this code appears to create three separate lines:

x = [0:10,NaN,20:30,NaN,40:50];
y = [0:10,NaN,0:10,NaN,0:10];
line(x,y)

Modify Data Instead of Creating New Objects

To view different data on what is basically the same graph, it is more efficient to update the data of the existing objects (lines, text, etc.) rather than recreating the entire graph.

For example, suppose you want to visualize the effect on your data of varying certain parameters.

  1. Set the limits of any axis that can be determined in advance, or set the axis limits modes to manual.

  2. Recalculate the data using the new parameters.

  3. Use the new data to update the data properties of the lines, text, etc. objects used in the graph.

  4. Call drawnow to update the figure (and all child objects in the figure).

For example, suppose you want to update a graph as data changes:

figure
z = peaks;
h = surf(z);
drawnow 
zlim([min(z(:)), max(z(:))]);
for k = 1:50
   h.ZData = (0.01+sin(2*pi*k/20)*z);
   drawnow
end