DEV Community

loading...

How can I cache output of a method's parameters, so I don't have to create a new object when the input(s) are the same?

baenencalin profile image Calin Baenen ・1 min read

I'm working on Janky in C#, and I have a JankyToken class. I'm gonna be making a lot of JankyTokens, so I need to know, how can I make a method (Create) of JankyToken that will cache it?

This is what I have so far:

// NOTE: `Type` is short for `JankyToken.Type` which is an
// enum that describes the token (e.g. `GT`, `LTEQ`, `ASS`, etc...).

/**
* @param type The type of token.
* @param value Additional data that describes custom tokens (e.g. Identifiers).
*/
public JankyToken Create(Type type, String value) {
    cache = /* Some method of retrieving the cached params */;
    if(cache != null) return cache;
    else {
        result = new JankyToken(type, value);
        /* Some method of caching the result */
        return cache;
    }
}
Enter fullscreen mode Exit fullscreen mode

Thanks!
Cheers!

Discussion (4)

pic
Editor guide
Collapse
podobaas profile image
Aleksey Podoba

This is a simple implementation of cache.
If you use threads, then better use Concurrent Dictionary.
docs.microsoft.com/dotnet/api/syst...

For example:

    public class MyClass
    {
        private Dictionary<string, JankyToken> _cache = new();

        public JankyToken Create(Type type, string val)
        {
            var key = $"{type}_{val}";

            if(_cache.ContainsKey(key))
            {
                return _cache[key];
            }
            else
            {
                var result = new JankyToken(type, val);
                _cache.Add(key, result);

                return result;
            }
        }
    }
Enter fullscreen mode Exit fullscreen mode
Collapse
baenencalin profile image
Calin Baenen Author

What if I want to retain the original value(s) of the parameters, like Python's LRU cache?

Collapse
podobaas profile image
Aleksey Podoba • Edited

I'm not good at Python, but if I understood you correctly, you have need retain Type type and string val into cache. In this case you can define a new class and implements properties for these params or use Tuple types.
ASP.NET Core or .NET 5 have ready implementation of cache

For example

    public class MyParams
    {
        public MyParams(Type type, string val)
        {
            Type = type;
            Val = val;
        }

        public Type Type { get; }

        public string Val { get; }
    }
Enter fullscreen mode Exit fullscreen mode

Or for C# 9

    public class MyParams
    { 
        public Type Type { get; init;}

        public string Val { get; init;}
    }
Enter fullscreen mode Exit fullscreen mode
public JankyToken Create(MyParams myParams)
Enter fullscreen mode Exit fullscreen mode
Thread Thread
baenencalin profile image
Calin Baenen Author

Okay. Thanks for your help.