Click here to Skip to main content
Click here to Skip to main content
Add your own
alternative version
Go to top

A Calculation Engine for .NET

, 1 Sep 2013
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
                    _dct.Remove(k)
                    done = False
                    Exit For
                End If
            Next
        Loop
    End Sub


    ' Properties
    Default Public ReadOnly Property Item(ByVal expression As String) As Expression
        Get
            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
                    RemoveDeadReferences()
                    _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.

License

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

Share

About the Author

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

| Advertise | Privacy | Mobile
Web04 | 2.8.140926.1 | Last Updated 1 Sep 2013
Article Copyright 2011 by Bernardo Castilho
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid