Click here to Skip to main content
15,884,836 members
Articles / Programming Languages / C#

A Calculation Engine for .NET

Rate me:
Please Sign up or sign in to vote.
4.92/5 (183 votes)
1 Sep 2013Public Domain15 min read 647.7K   11.4K   421  
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 A Public Domain dedication


Written By
Software Developer
Brazil Brazil
Software Architect/Developer with several years experience creating and delivering software.

Full-stack Web development (including React, Firebase, TypeScript, HTML, CSS), Entity Framework, C#, MS SQL Server.

Passionate about new technologies and always keen to learn new things as well as improve on existing skills.

Comments and Discussions