A real-world example contrasting the inefficient loop with the high-performance 'Parse-Once' pattern using a changing variable.

ID: 1193

				
					using uCalcSoftware;

var uc = new uCalc();
var x_var = uc.DefineVariable("x");
var i = 0;

// --- Inefficient Way ---
Console.WriteLine("--- Inefficient: Eval() in a loop ---");
for ( i = 1; i <= 3; i++) {
   x_var.Value(i);
   Console.WriteLine(uc.Eval("x * x + 2"));
}

Console.WriteLine("");

// --- High-Performance Way ---
Console.WriteLine("--- Efficient: Parse() once, Evaluate() in a loop ---");
// Parse outside the loop
var expr = uc.Parse("x * x + 2");
for ( i = 1; i <= 3; i++) {
   x_var.Value(i);
   // Evaluate the pre-parsed object
   Console.WriteLine(expr.Evaluate());
}
				
			
--- Inefficient: Eval() in a loop ---
3
6
11

--- Efficient: Parse() once, Evaluate() in a loop ---
3
6
11
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   auto x_var = uc.DefineVariable("x");
   auto i = 0;

   // --- Inefficient Way ---
   cout << "--- Inefficient: Eval() in a loop ---" << endl;
   for ( i = 1; i <= 3; i++) {
      x_var.Value(i);
      cout << uc.Eval("x * x + 2") << endl;
   }

   cout << "" << endl;

   // --- High-Performance Way ---
   cout << "--- Efficient: Parse() once, Evaluate() in a loop ---" << endl;
   // Parse outside the loop
   auto expr = uc.Parse("x * x + 2");
   for ( i = 1; i <= 3; i++) {
      x_var.Value(i);
      // Evaluate the pre-parsed object
      cout << expr.Evaluate() << endl;
   }
}
				
			
--- Inefficient: Eval() in a loop ---
3
6
11

--- Efficient: Parse() once, Evaluate() in a loop ---
3
6
11
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      Dim x_var = uc.DefineVariable("x")
      Dim i = 0
      
      '// --- Inefficient Way ---
      Console.WriteLine("--- Inefficient: Eval() in a loop ---")
      For i  = 1 To 3
         x_var.Value(i)
         Console.WriteLine(uc.Eval("x * x + 2"))
      Next
      
      Console.WriteLine("")
      
      '// --- High-Performance Way ---
      Console.WriteLine("--- Efficient: Parse() once, Evaluate() in a loop ---")
      '// Parse outside the loop
      Dim expr = uc.Parse("x * x + 2")
      For i  = 1 To 3
         x_var.Value(i)
         '// Evaluate the pre-parsed object
         Console.WriteLine(expr.Evaluate())
      Next
   End Sub
End Module
				
			
--- Inefficient: Eval() in a loop ---
3
6
11

--- Efficient: Parse() once, Evaluate() in a loop ---
3
6
11