Can I memoize a Generic Method?

南笙酒味 提交于 2020-01-01 06:57:08

问题


I have 2 expensive Generic methods:

  public T DoStuff<T>()
  {
      //return depends on T.
  }

  public T DoStuffBasedOnString<T>(string input)
  {
      //return depends on T.
  }

Their return values can never vary for a given Type and string.

Is it possible to memoize these functions?


My starting point is a memoize function taken from here: https://www.aleksandar.io/post/memoization/

public static Func<T, TResult> Memoize<T, TResult>(this Func<T, TResult> f)
{
    var cache = new ConcurrentDictionary<T, TResult>();
    return a => cache.GetOrAdd(a, f);
}

来源:https://stackoverflow.com/questions/56269443/can-i-memoize-a-generic-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!