Wrench value from your Creo Investments Home Measure the benefits Simple Automation can bring Why
Automate?
A personal way to do PDM Peer to Peer
PDM
3D Drawings Model Based
Design
Smooth out unwanted sharp edges Other
Articles
www.proetoolbox.co.uk - Simple Automation made Simple

Creating Efficient Loops

Most users construct the for() loop in a way that results in an extra evaluation step for each loop. This article points out that the for() loop can be constructed differently such that the evaluation does not need to occur.

//I've got two variables
// JSArray - Is a regular JavaScript Array
// WLSequence - Is a Pro/Web.Link sequence Object

//Want to loop around the JS Array and WL Sequence
for (var i=0;i<WLSequence.Count;i++)
{
	var CurItem = WLSequence.Item(i);
	for (var j=0;j<JSArray.length;j++)
	{
		var Info = CurItem[JSArray[j]];
	}
}

The Basic Method

In the example code (shown right) the loop is constructed for (var i=0;i<WLSequence.Count;i++){}. The statement has three sections, the first is an initialisation section which executes once at the start of the loop. The second section is an evaluation section and is evaluated at the end of the loop and if the result is true the third section is executed and the loop continued.

//I've got two variables
// JSArray - Is a regular JavaScript Array
// WLSequence - Is a Pro/Web.Link sequence Object

//Want to loop around the JS Array and WL Sequence
for (var i=0, z=WLSequence.Count;i<z;i++)
{
	var CurItem = WLSequence.Item(i);
	for (var j=0, y=JSArray.length;j<y;j++)
	{
		var Info = CurItem[JSArray[j]];
	}
}

The More Efficient Loop

The problem is that evaluating a property of an object requires more processing time than simply comparing two regular JavaScript variables.

Notice how the code right instead defines another variable in the first section (y=JSArray.length) which extracts the Array length. Thus the longer operation is done first and more importantly, done once. Then the middle evaluation (j<y) is simply comparing two regular types which is faster.

Conclusion

When your loops run tens of thousands of times it pays dividends to tune them as much as possible. This simple trick shaves a few miliseconds per loop to help bring execution time down.