Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add caching to DefaultTypeResolver (issue #437) #447

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 11 additions & 5 deletions src/KafkaFlow.Serializer/DefaultTypeResolver.cs
Original file line number Diff line number Diff line change
@@ -1,18 +1,22 @@
namespace KafkaFlow
{
using System;
using System.Collections.Concurrent;

internal class DefaultTypeResolver : IMessageTypeResolver
{
private const string MessageType = "Message-Type";

private static readonly ConcurrentDictionary<string, Type> ConsumeTypeCache = new(StringComparer.Ordinal);
private static readonly ConcurrentDictionary<Type, string> ProduceTypeCache = new();

public Type OnConsume(IMessageContext context)
{
var typeName = context.Headers.GetString(MessageType);

return typeName is null ?
null :
Type.GetType(typeName);
null :
ConsumeTypeCache.GetOrAdd(typeName, Type.GetType);
}

public void OnProduce(IMessageContext context)
Expand All @@ -24,9 +28,11 @@ public void OnProduce(IMessageContext context)

var messageType = context.Message.Value.GetType();

context.Headers.SetString(
MessageType,
$"{messageType.FullName}, {messageType.Assembly.GetName().Name}");
string messageTypeName = ProduceTypeCache.GetOrAdd(
messageType,
static messageType => $"{messageType.FullName}, {messageType.Assembly.GetName().Name}");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see benefits in using a Type cache on message consumption to avoid the Type.GetType call. But when producing I don't know if we will have a performance benefit changing from a string concatenation to a dictionary search.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think when producing there will be no performance benefit but rather a memory allocations benfit.


context.Headers.SetString(MessageType, messageTypeName);
}
}
}
Loading