Search code examples
vb.netperformancepropertiesencapsulation

VB.NET property get and cache


If I use in VB.NET a property get of this shape:

Public ReadOnly Property Thing(i as long) as double(,)
    Get
        Return SomeCalculation(i )
    End Get
End Property

and the code calls many times the property get with the same i (after doing the same with another iscen and so on), will the result be cached until I use a new i or will it be recalculated each time?

Thanks!


Solution

  • No there is no automatic caching in VB.NET to store the result of repeated calculations. It is up to you to provide some kind of caching.

    For example you can use a Dictionary

     Dim cache As Dictionary(Of Long, Double(,)) = New Dictionary(Of Long, Double(,))
    
    Public ReadOnly Property Thing(i as long) as double(,)
        Get
           Dim result As Double(,)
           If Not cache.TryGetValue(i, result) Then
               result = SomeCalculation(i)
              cache.Add(i, result)
           End If
           Return result
       End Get
    End Property
    

    Of course,as any simple solution, there are some points to consider:

    • There is no invalidation rule (the cache remains active for the lifetime of the app)
    • It assumes that the calculation produces always the same result for the same input