Specific Powershell: opposite of 'new'

Hello,

in a powershell script I have this:

$days = [DateTime[]]::new( 16 )

what is the correct statement to free the allocated memory?

I don’t think it is just this:

$days = $null

Thanks

Assuming you are in some scenario where the memory allocation is a serious issue, I would suggest looking at Remove-Variable

You can also force garbage collection.

[System.GC]::Collect()

That would create an array of 16 DateTime structures. Arrays are reference objects so the memory would be allocated in the heap. A reference to the array would be stored on the stack, but not the stack that a “C” programmer would use . . . it’s one that PowerShell itself manages.

The reference occupies a pretty small footprint in the stack (probably about 8 bytes for the data and another few bytes that PowerShell uses to manage the variable).

Using either Remove-Object days or $days=$null will remove the reference to the array, but the space allocated for the variable is just reused, not freed.

The heap memory will, eventually, be reclaimed by the .Net garbage collection. You can, as @neemobeer noted, trigger the garbage collection but there isn’t a way to force the actual reduction. The garbage collection process will eventually take care of that.

The best you can do (without messing around with the MinWorkingSet and MaxWorkingSet) is:

[GC]::Collect
[GC]::WaitForPendingFinalizers()
[GC]::Collect()
1 Like
Remove-Variable -Name days