Comparison of two ways to initialize JComboBox

 

method one

 

JComboBox comboBox = new JComboBox();
		long t1 = System.currentTimeMillis();
		for (int i = 0; i < 10000; i++) {
			comboBox.addItem(new Integer(i));
		}
		long t2 = System.currentTimeMillis();
		System.out.println(t2-t1);

t2-t1=1ms

 

 

 Method 2

 

long t1 = System.currentTimeMillis();
		Vector v = new Vector(10000);
		for (int i = 0; i < 10000; i++) {
			v.add(new Integer(i));
		}
		ComboBoxModel model = new DefaultComboBoxModel(v);
		comboBox.setModel(model);
		long t2 = System.currentTimeMillis();
		System.out.println(t2-t1);

 

 t2-t1=40ms

 

 

illustrate:

The way is to simply add data items to the JComboBox. This method is fine for small data volumes, but it becomes obviously very slow when adding a large amount of data.

Although the code in mode 1 does not explicitly reference any model, the JComboBox's model object actually participates in this process, and every time addItem is called, a number of operations happen inside the JComboBox:

The component passes the request to the JComboBox's model, and the model sends an event indicating that a new item has been added.

 

The second way is faster for two reasons.

First, because all items are added to the model at once, rather than one by one, only one event is emitted, which means fewer events are fired and fewer method calls.

Second, because fewer objects need to be notified of changes, the total workload is equal to the number of triggers multiplied by the number of listeners. Because the model is newly created, there are zero listeners listening on it, which means that no triggering event happened.

 

Two things can be learned from the above example:

Use batch operations whenever possible to minimize the number of triggering events.

When initializing or completely replacing the content of the model, consider regenerating the model, do not use the existing model, there are already many listeners on the existing model, and the newly generated model has no listeners, which avoids unnecessary call of the handler function.

 

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326771235&siteId=291194637