if i have a loop and an if...then statement inside that loop with a variable being dimmed inside the if...then, will that waste memory?
Printable View
if i have a loop and an if...then statement inside that loop with a variable being dimmed inside the if...then, will that waste memory?
If this is similar to what you are trying to do , then Yes , it's waste of memory . Here , in below example , the variable 'aa' will be dimmed 5 times if the first condition was met otherwise nothing happen .
VB Code:
Dim i As Integer Dim a As String = "a", b As String = "b" For i = 0 To 5 If a = "a" Then Dim aa As String = "a" 'do other stuff ElseIf b = "b" Then 'do something End If Next
i thought it was different in .net where the variable was destroyed once it's container finished, for..loop, if..then, procedure... guess not. thanks though
Actual gmatteson you are correct the variable scope is only valid inside the If statement. Although it will be initialized 5 times or with each loop, but it will also be destroyed in that loop. So if you only need it for something inside that if..then then that is the proper way to do it.
Hmm , still wasting memory :confused: .
:)
Well it doesn't waste memory because it only creates the the variable or takes the memory if the IF statement is true and then it uses it and then destroys it. It is most efficent since no memory is used if not needed and instead of 5 there is one 1 at a time. If you created it outside of the then it would be used regardless of whether or not it was needed.
But say the GC doesn't collect the objects until after the looping has completed, then you would still have the memory allocated until that point. Or at least, the GC has more work to do.
Hope I don't start another GC debate :D
And say loop is long , still wasting memory in my view point :confused: . This doesn't mean you guys are wrong but as I know , it's bad practice to dim variables within loops and IFs with some exceptions of course .Quote:
Originally posted by VBCrazyCoder
But say the GC doesn't collect the objects until after the looping has completed, then you would still have the memory allocated until that point. Or at least, the GC has more work to do.
Hope I don't start another GC debate :D
lol.......:DQuote:
[i]
Hope I don't start another GC debate :D [/B]
Wouldn't a locally declared variable like that be created on the stack? If that is the case, there is no waste of memory, since the memory is already allocated (this might be true even without the stack), and the object goes away when the function or the loop exits.