Given the following C# code inside a function:
....
var documentCollection =
client.CreateDocumentCollectionQuery("dbs/" + database.Id)
.Where(c => c.Id == DocumentCollectionName)
.AsEnumerable()
.FirstOrDefault();
if (documentCollection == null)
{
documentCollection =
await
client.CreateDocumentCollectionAsync(
"dbs/" + database.Id,
new DocumentCollection { Id = DocumentCollectionName });
}
return client;
Note: I'm not returning the documentCollection
, I just need it to be initialized, if not already ( the CreateDocumentCollectionAsync
call ). So - after the if
block , documentCollection
becomes an unused variable.
Now - ReSharper proposes to optimize this to:
var documentCollection =
client.CreateDocumentCollectionQuery("dbs/" + database.Id)
.Where(c => c.Id == DocumentCollectionName)
.AsEnumerable()
.FirstOrDefault()
?? await
client.CreateDocumentCollectionAsync(
"dbs/" + database.Id,
new DocumentCollection { Id = DocumentCollectionName });
And indicates now that documentCollection
is an unused variable.
My question: will C# code optimization or a 'release' build completely remove this line of code and result in the CreateDocumentCollectionAsync
to never fire?
The C# optimization course taught me that 'release' builds garbage collect variables as soon as they're not needed 'down the line' in the function, whereas debug builds don't do that (for debugging purposes).
I'm now wondering whether it's so eager even that it optimizes away an unused variable assignment (which triggers an operation in the background).
No, neither the compiler, nor JIT, will optimize your method call away.
There is a list of what the JIT compiler does. It does optimize away if (false) { ... }
blocks for example, or unused variable assignments. It does not just optimize away your method calls. If that was true, every call to a void
method should be gone too.
No.
Any optimiser may only remove code that has no observable behaviour.
Otherwise it's not an optimiser.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With