Click here to Skip to main content
11,411,494 members (65,570 online)
Click here to Skip to main content
Add your own
alternative version

A Calculation Engine for .NET

, 1 Sep 2013 CPOL
A calculation engine that is small, fast, and extensible.
''' <summary>
''' Caches expressions based on their string representation.
''' This saves parsing time.
''' </summary>
''' <remarks>
''' Uses weak references to avoid accumulating unused expressions.
''' </remarks>
Friend Class ExpressionCache

    ' Fields
    Private _ce As CalcEngine
    Private _dct As Dictionary(Of String, WeakReference)
    Private _hitCount As Integer

    ' Methods
    Public Sub New(ByVal ce As CalcEngine)
        _ce = ce
        _dct = New Dictionary(Of String, WeakReference)
    End Sub

    Private Sub RemoveDeadReferences()
        Dim done As Boolean = False
        Do While Not done
            done = True
            Dim k As String
            For Each k In _dct.Keys
                If Not _dct.Item(k).IsAlive Then
                    done = False
                    Exit For
                End If
    End Sub

    ' Properties
    Default Public ReadOnly Property Item(ByVal expression As String) As Expression
            Dim wr As WeakReference
            If (_dct.TryGetValue(expression, wr) AndAlso wr.IsAlive) Then
                Return TryCast(wr.Target, Expression)
            End If
            If ((Not wr Is Nothing) AndAlso (_dct.Count > 100)) Then
                _hitCount = _hitCount + 1
                If (_hitCount > 100) Then
                    _hitCount = 0
                End If
            End If
            Dim x As Expression = _ce.Parse(expression)
            _dct.Item(expression) = New WeakReference(x)
            Return x
        End Get
    End Property
End Class

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Bernardo Castilho
Chief Technology Officer ComponentOne
United States United States
No Biography provided

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150414.5 | Last Updated 1 Sep 2013
Article Copyright 2011 by Bernardo Castilho
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid