Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

200
Vistas
Does string interpolation evaluate duplicated usage?

If I have a format string that utilizes the same place holder multiple times, like:

emailBody = $"Good morning {person.GetFullName()}, blah blah blah, {person.GetFullName()} would you like to play a game?";

does person.GetFullName() get evaluated twice, or is the compiler smart enough to know these are the same value, and should be evaluated once?

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

Yes, it will be evaluated twice. It can't know that it is the same value. For example:

Random rng = new Random();
Console.WriteLine($"{rng.Next(5)}, {rng.Next(5)}, {rng.Next(5)}");

It's exactly the same as if you just used the expression as a method argument - if you called:

Console.WriteLine("{0} {1}", person.GetFullName(), person.GetFullName());

... you'd expect GetFullName to be called twice then, wouldn't you?

If you only want to evaluate it once, do so beforehand:

var name = person.GetFullName();
emailBody = $"Good morning {name}, blah blah blah, {name} would you like to play a game?";

Or just use a normal string.Format call:

emailBody = string.Format(
    "Good morning {0}, blah blah blah, {0} would you like to play a game?",
    person.GetFullName());
over 4 years ago · Santiago Trujillo Denunciar

0

is the compiler smart enough to know these are the same value [...]?

But it won't necessarily be the same value. The method could very well return different results on subsequent invocations, so it can't cache the result.

over 4 years ago · Santiago Trujillo Denunciar

0

Most of the time, the compiler will be able to optimize this. Unfortunately, the times it can't are also the times you would care most.

Optimization in this context is not based on calling the same function twice, but based on inlining. Accessors usually are trivial (looking up a field, or at most doing a conversion between numeric types or format/parse between numeric and string type) and as such, easily meet the criteria for inlining. Furthermore, the JIT prevents problems with cross-module inlining. On the other hand, interfaces, delegates, and virtual calls can prevent inlining.

Once the compiler has replaced both calls by the function body, it sees two loads from the same field, and likely can use common subexpression optimization to actually fetch the field only once (as long as it can prove there is no intervening write from the same thread... in particular it doesn't have to worry about writes from other threads unless there's an intervening lock).

But this only saves an extra field fetch. In cases where the accessor call is expensive (remote procedure call or database lookup), inlining won't be possible, and you're going to pay for two evaluations. In such a case caching the result yourself is worthwhile.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda