Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will C# compiler and optimization break this code?

Tags:

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).

like image 437
Jochen van Wylick Avatar asked Jan 06 '16 09:01

Jochen van Wylick


2 Answers

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.

like image 59
Patrick Hofman Avatar answered Sep 30 '22 23:09

Patrick Hofman


No.

Any optimiser may only remove code that has no observable behaviour.

Otherwise it's not an optimiser.

like image 16
Lightness Races in Orbit Avatar answered Sep 28 '22 23:09

Lightness Races in Orbit