Poi Lu
Poi Lu

Reputation: 88

Powershell reference type memory consumption

Powershell reference consumes a lot more memory than barely declare a variable, which is weird, it supposes to consume less.


Store with object
- it consumes less memory

Store with ref of object
- it consumes 2x memory than not using memory


I guess it is the class causing this, but I don't know why.

class LinkedListNode {
    $value
    $next = @()
    $previous = @()

    LinkedListNode($value) {
        $this.value = $value
    }
}

class test {
    $hash = @{}

    [object] Append($value) {
        $newNode = New-Object LinkedListNode $value
        $newNode.previous = $null
        $newNode.next = $null
        $this.hash.Add($value, [ref] $newNode)    # with ref
        # $this.hash.Add($value, $newNode)        # with object
        return $this
    }

}

$t = [test]::new()
for ($i = 0; $i -lt 30000; $i++) {
    $t.Append($i)
}

For the code below, ref consumes less memory, which I think is usual case.

for ($i = 0; $i -lt 30000; $i++) {
    $testObject = New-Object -TypeName PSObject -Property @{
        'forTest' = "test"
    }
    $test.Add($i, [ref] $testObject)    # with ref
    # $test.Add($i, $testObject)        # with object
}

Upvotes: 1

Views: 152

Answers (1)

HAL9256
HAL9256

Reputation: 13483

This is a tricky one because references in PowerShell aren't the same as C++ references, and don't do what you think they do. Basically, when you read about_Ref it indicates that it treats Variables and Objects differently.

Passing a variable of type int can be by reference or by value.

Passing an Object is always by reference.

What that means, is that the example you used:

The "by Object" used a true reference.

The "by Ref" actually wrapped the LinkedListNode object in a System.Management.Automation.PSReference object. This System.Management.Automation.PSReference object takes up some space, and due to the small object sizes, made it "seem" like it took up twice the memory.

The [ref] is meant for interacting with .NET functions that require it see: [ref] doesn't work with class members and Restrict use of [ref] to variables

Also, using [ref] with functions in PowerShell:

When passing a variable by reference, the function can change the data and that change persists after the function executes.

This is different than how C++ would use references.

Upvotes: 1

Related Questions