How C# 10 “fixed” string interpolation

preview_player
Показать описание

Hello everybody I'm Nick and in this video I will show you how the introduction of InterpolatedStringHandlers in C# 10 and .NET 6 completely change the way we think about them. Not only is string interpolation significantly more efficient now when it comes to speed and memory, but you can also create your own InterpolatedStringHandlers to completely eliminate allocations in some cases.

Timestamps
Intro - 0:00
The problem - 0:38
How Microsoft fixed it - 3:00
How you can build your own - 8:17

Don't forget to comment, like and subscribe :)

Social Media:

#csharp #dotnet #performance
Рекомендации по теме
Комментарии
Автор

I have long saved development videos, but only the very best -- videos with content that is useful, interesting, high-quality, and not trivially found with a web search.
I find that list has grown by nearly every video I have seen on your channel. Your to-the-point, in-depth, not-afraid-to-be-technical format and your passionate approach to real world challenges and solutions, acknowledging how awesome C# is but without the immature wall of isolationism developers often build around their favorite solutions, is prime-grade YouTube content.

CharlesBurnsPrime
Автор

I think it's important to point out that .NET 6 interpolated strings are now compiled to that new `ref struct` type that is implicitly cast to string. Realizing this made understanding this topic much easier for me. Other than that, thanks for the explanation!

TheLeftExitNET
Автор

It's great to see how your voice and facials expressions change when you are showing something as cool as this. It makes feel the one listening to be excited about what you are showing too. Thanks for showing this level of enjoyment and keep up the good work.

col_rod
Автор

This is some really insane (read: awesome) stuff. Thanks for showing.

krccmsitp
Автор

Whoa, I haven't been following closely the more recent additions to C# since 10 but man... it's turning out to be one of my favorite updates. Just discovered InterpolatedStringHandlers (and your video) today but the mention of the CallerArgumentExpression is another jawdropping addition to me. That actually solves a problem I had for a feature I needed to implement. Looks like I'll need to go back and look through all the changes to see what else I'm missing.

Appl_Jax
Автор

As clear as it ever could be! Great job, thank you!

evgeny
Автор

I'm curious if entity framework's latest iterations have applied this kind of optimization considering the massive amount of string building or interpolating involved in creating sql statements.

dannystaten
Автор

Να ΄σαι καλά ρε Νικόλα για την γνώση που

thanasakis
Автор

What I don't like about features like these is that they have no contract on declarations/definitions. They are not implementing an interface or extending a class, or using some sort of other way to ensure, that you're implementing such features correctly. The same is with async/await and GetAwaiter/Awaiter class, or the Deconstruct method. It's basically "convetion-based". Other than that, I love language features, which compile into something more, but still let you customize what it compiles into. It makes the code clean, more readable, but still optimized. I believe it's also possible to customize the async method builder, would love a video about that. Thanks for great content!

BrokoIis
Автор

I have an implementation for logging ^^.
You can pass a normal interpolated string to a log method and it will generate a state to create the message or provide all values for structured logging.
The performance is not as good as generated logging (you explained it in your last video) and for a "real world" software I would still use the generated logging, but it's cool :D

And it would be possible to create SQL statements in code with string interpolation and nobody can "forget" the parameters because the handler adds them automatically.

Palladin
Автор

I love this, can see how this would be very beneficial for logging conditionally and enabling logging middlewares to determine if it should log or not instead of having to wrap the code in extensions etc

fieryblast
Автор

The only thing I know how to code is a window with an exit function in Visual Basic on Windows XP, this video was entertaining yet absolute gibberish.

Wilsoncommeleballon
Автор

Have you done a video on IO pipelines and/or channels? I had to use those recently and definitely would like to learn more about them. Thanks for the great vids!

brandonsquires
Автор

Thanks again for your videos, Nick! You help me a lot.

xavier.xiques
Автор

Thanks for explaining. Great that they fixed it!

ChristofferLund
Автор

Well, now I wonder if you were to combine what you've shown us here with your logging optimization, would it actually be faster to use string interpolation? Either way, thanks for the video!

davidheale
Автор

Damn, you are pretty knowledgeable.

Only be careful with microbenchmarks, loop alignment is a big thing in this scenarios.
Especially when comparing .net 5 (basically no loop alignment) and 6 (optimized loop alignment).
In .net 5, changing the order of methods in the class can lead to different benchmark results.

frddyfrsh
Автор

Though all that is saiud in the video here is technically correct, I think it is a very complicated and not very transparent way to achive the goal.
I normally use a Func<string> argument in cases, where I want/need to think about performance - run time here.
I have inserted a short demo to present my case below (though Youtube chat formatting isn't good for that).

The time improvement in this case is above 99%, though I have not benchmarked memory consumption, so I have no idea if there is a difference here.

using System;
using System.Diagnostics;

namespace StringConcatPerformance
{
class Program
{
/// <summary>
/// Standard way to call method with string argument
/// </summary>
/// <param name="showMessage">If false the message argument will not be used at all</param>
/// <param name="message">Represents some string, that it has taken some time to build</param>
public static void NormalMethod(bool showMessage, string message)
{
if (showMessage) Console.WriteLine(message);
}

/// <summary>
/// Alternative way to call method with string-returning function argument
/// </summary>
/// <param name="showMessage">If false the messageFunc argument will not be used at all</param>
/// <param name="messageFunc">A function, that, but only if showMessage argument is true, build and return a string value when called</param>
public static void FuncedMethod(bool showMessage, Func<string> messageFunc)
{
if (showMessage)
}


static void Main(string[] args)
{
// Example of how to call "the old way" and as Func-argument
NormalMethod(false, $"This string is created at {DateTime.Now:yyyyMMDD HHmmss.fff}");
FuncedMethod(false, () => $"This string is created at {DateTime.Now:yyyyMMDD HHmmss.fff}");

// Simple Stopwatch times benchmark test. Call both methods a lot of times but never actually use the Message/MessageFunc arguments
var calls =
var watch = new Stopwatch();

watch.Reset();
watch.Start();
for (var i = 0; i < calls; i++)
NormalMethod(false, $"{i}'th call, {DateTime.Now:yyyyMMDD HHmmss.fff}");
watch.Stop();
var normal = watch.ElapsedMilliseconds;

watch.Reset();
watch.Start();
for (var i = 0; i < calls; i++)
FuncedMethod(false, () => $"{i}'th call, {DateTime.Now:yyyyMMDD HHmmss.fff}");
watch.Stop();
var funced = watch.ElapsedMilliseconds;

Console.WriteLine(@$"{calls} calls Normal: {normal} msec, Funced: {funced} msec");
{(100 - 100.0 * funced/normal):N02}% saved with FuncedMethod");
}
}
}

Rynas
Автор

Doesnt this completely change your recent logging video? Amazing stuff. Thanks for sharing

T___Brown
Автор

Is there a similar extension for VS that shows what we see on 3:11

evtimstefanov
visit shbcf.ru