Decrease the Calculation Time of Cell.Calculate method

Possible Usage Scenarios

Normally, we recommend users to call Workbook.CalculateFormula() method once and then get the calculated values of the individual cells. But sometimes, users do not want to calculate entire workbook. They just want to calculate a single cell. Aspose.Cells provides CalculationOptions.Recursive property which you can set to false and it will decrease the calculation time of individual cell significantly. Because when the recursive property is set to true, then all the dependents of cells are recalculated on each call. But when the recursive property is false, then dependent cells are calculated only once and are not calculated again on subsequent calls.

Decrease the Calculation Time of Cell.Calculate() method

The following sample code illustrates the usage of CalculationOptions.Recursive property. Please execute this code with the given sample excel file and check its console output. You will find that setting the recursive property to false has decreased the calculation time significantly. Please also read the comments for a better understanding of this property.

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// Test calculation time after setting recursive true
TestCalcTimeRecursive(true);
// Test calculation time after setting recursive false
TestCalcTimeRecursive(false);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
static void TestCalcTimeRecursive(bool rec)
{
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Load your sample workbook
Workbook wb = new Workbook(dataDir + "sample.xlsx");
// Access first worksheet
Worksheet ws = wb.Worksheets[0];
// Set the calculation option, set recursive true or false as per parameter
CalculationOptions opts = new CalculationOptions();
opts.Recursive = rec;
// Start stop watch
Stopwatch sw = new Stopwatch();
sw.Start();
// Calculate cell A1 one million times
for (int i = 0; i < 1000000; i++)
{
ws.Cells["A1"].Calculate(opts);
}
// Stop the watch
sw.Stop();
// Calculate elapsed time in seconds
long second = 1000;
long estimatedTime = sw.ElapsedMilliseconds / second;
// Print the elapsed time in seconds
Console.WriteLine("Recursive " + rec + ": " + estimatedTime + " seconds");
}

Console Output

This is the console output of the above sample code when executed with the given sample excel file on our machine. Please note, your output may differ but the elapsed time after setting the recursive property to false will always be less than setting it to true.

Recursive True: 96 seconds

Recursive False: 42 seconds