[BUG] Performance issue in For<T>(client, builder) and For(refitInterfaceType, client, builder) of Refit.RestService
Describe the bug RestService uses ConcurrentDictionary to cache pairs of <Refit REST interface, Refit Generated Client Proxy>.
ConcurrentDictionary.GetOrAdd provides the following overloads
-
GetOrAdd(TKey, Func<TKey,TValue>) - Adds a key/value pair to the ConcurrentDictionary<TKey,TValue> by using the specified function if the key does not already exist. Returns the new value, or the existing value if the key exists.
-
GetOrAdd(TKey, TValue) - Adds a key/value pair to the ConcurrentDictionary<TKey,TValue> if the key does not already exist. Returns the new value, or the existing value if the key exists.
The current code of For<T>(client, builder) and For(refitInterfaceType, client, builder) use the GetOrAdd(TKey, TValue) overload. That completely removes the usefulness of the cache.
Steps To Reproduce n/a
Expected behavior Regardless on number of times the For<T>(client, builder) or For(refitInterfaceType, client, builder) are called for a given type (T), GetGeneratedType should be called only once per type.
Screenshots Current code (calculates a value on every call):
public static T For<T>(HttpClient client, IRequestBuilder<T> builder)
{
var generatedType = TypeMapping.GetOrAdd(typeof(T), GetGeneratedType<T>());
return (T)Activator.CreateInstance(generatedType, client, builder);
}
public static object For(Type refitInterfaceType, HttpClient client, IRequestBuilder builder)
{
var generatedType = TypeMapping.GetOrAdd(refitInterfaceType, GetGeneratedType(refitInterfaceType));
return Activator.CreateInstance(generatedType, client, builder);
}
Environment n/a
Additional context Here is a fix (using a delegate to calculate a value when a new entry should be added):
public static T For<T>(HttpClient client, IRequestBuilder<T> builder)
{
var generatedType = TypeMapping.GetOrAdd(typeof(T), (type) => GetGeneratedType(type));
return (T)Activator.CreateInstance(generatedType, client, builder);
}
public static object For(Type refitInterfaceType, HttpClient client, IRequestBuilder builder)
{
var generatedType = TypeMapping.GetOrAdd(refitInterfaceType, (type) => GetGeneratedType(type));
return Activator.CreateInstance(generatedType, client, builder);
}
@pit-hub can you please submit a PR?
@pit-hub can you please submit a PR?
Hi @onovotny as @yuri-voloshyn did some work about it on PR: #663. In my turn I've made some improvements to it's PR. More details here: PR 663
@pit-hub can you please submit a new PR? I do prefer not to modify state on the HttpClient instance for the reasons you mentioned.
This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.