bakre381
bakre381

Reputation: 35

Disposing objects

How does the GC dispose objects created in the following 2 scenarios?

1)

Private Function DoSomething() As Boolean
   Return New DatabaseManager().Insert()
End Function

2)

Private Function DoSomething() As Boolean
   Dim mngr As New DatabaseManager()
   Return mngr.Insert()
End Function

In Option 1, I don't create local variable to hold the reference of the object. In Option 2, I hold the reference in local variable.

What option is better and why? (if any)

Upvotes: 0

Views: 115

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038820

As you can see, in the option 1, i dont create local variable to hold the reference of the object

You might not be creating it explicitly but believe me at the IL level which is what the compiler emits there is an instance of the object created because you cannot call an instance method on an object without an instance.

Those are equivalent in terms of garbage collection and probably the compiler will optimize it. And because they are equivalent of course the preferred is the one which involves less code and is more readable to you. For me it's the first but it could subjective, so it's really up to you.

Upvotes: 4

Hans Passant
Hans Passant

Reputation: 941515

There is no difference, the JIT compiler will generate the exact same machine code for both. The DataBaseManager object will be visible to the garbage collector, typically held in a CPU register as the Me reference inside the Insert method. Any GC that runs afterwards will clean it up.

Upvotes: 2

Related Questions