Vanguard Software
Forecasting & Planning Solutions
Home Products Solutions Services Customers Partners Company
 
Applying science to business management

contents.gifindex.gifprev1.gifnext1.gif

Optimizing Loops

If your application is consuming a significant amount of CPU time, it is most likely using the time inside loops. The best way to improve loop performance is to replace the loops with calls to specialized primitives or to use list and matrix processing.

For example, assume you start with the following code that calculates the sum of all integers squared from 1 to 100,000:

var total;
for(var n=1; n<=100000; n++)
total+=n*n;

One way to improve performance is to find a primitive that performs the function more efficiently. You can replace the code above using the sigma primitive as follows:

var total=sigma(n*n,n,1,100000);

In addition to sigma, you might be able to use each, both, or makelist.

Finally, consider using matrix math. The following expression is equivalent to both examples above:

var total=sum(1..100000^2);

The code using a for loop takes about 480 msec to execute on a particular test computer. In contrast, the example using sigma takes about 170 msec--almost a three to one improvement. The matrix math example takes about 240 msec to execute--a two to one improvement.

Matrix math is often very fast, but it is not very memory efficient. Both the for and sigma examples require a negligible amount of memory to calculate a solution. However, the matrix math example requires about 6MB of RAM for a very brief amount of time.

  Demand Planning  |  Financial Forecasting
Forecasting Software  |  Strategic Planning Software  |  Decision Tree Software
Decision Support Software  |  Expert System Software  |  Online Surveys

Contact Us  |  Terms of Use  |  Privacy Policy  |  Site Map
Vanguard Software
© 2011 Vanguard Software Corporation
Print this page   Email this page to a friend