与对象一起存储
-消耗更少的内存
使用对象的引用进行存储
-它消耗的内存是不使用内存的2倍
我想这是导致这种情况的类,但我不知道为什么。
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)
}
对于下面的代码,ref消耗的内存更少,我认为这是通常的情况。
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
}
答案 0 :(得分:1)
这是一个棘手的问题,因为PowerShell中的引用与C ++引用不同,并且不执行您认为的操作。基本上,当您阅读about_Ref时,它表示对变量和对象的区别。
可以通过引用或值来传递类型为int
的变量。
始终通过引用传递对象。
这意味着您使用的示例是
“按对象”使用了真实的引用。
“ by Ref”实际上将LinkedListNode
对象包装在System.Management.Automation.PSReference
对象中。这个System.Management.Automation.PSReference
对象占用了一些空间,并且由于对象尺寸较小,使其看起来像“占用”了两倍的内存。
[ref]
用于与需要它的.NET函数进行交互,请参见:[ref] doesn't work with class members和Restrict use of [ref] to variables
此外,将[ref]
与PowerShell中的功能配合使用:
通过引用传递变量时,该函数可以更改数据 并且该更改在函数执行后仍然存在。
这与C ++使用引用的方式不同。