C# 固定区域优化
c# fixed region optimizations
找不到关于此的任何信息,但如果我找到这样的代码
fixed(Foo* foo=bar) {
doSomething(bar); // not foo
}
其中 foo 未被引用,我能否确定 bar 在该区域内保持固定并且不会因优化而消失?
是的。这就是 fixed
语句的全部要点,正如规范中所述:
For each address computed by a fixed-pointer-initializer the fixed statement ensures that the variable referenced by the address is not subject to relocation or disposal by the garbage collector for the duration of the fixed statement. For example, if the address computed by a fixed-pointer-initializer references a field of an object or an element of an array instance, the fixed statement guarantees that the containing object instance is not relocated or disposed of during the lifetime of the statement.
在你的例子中,fixed-pointer-initializer 是 bar
。但是,出于语法原因,需要声明 foo
。这可能就是这个成语的原因,其中数组 bar
必须是不可移动的,但你并不真的需要指针。
附带说明:在这样的 fixed
语句之外,可以将 bar
移出它的内存位置并不是优化。这是垃圾收集器压缩堆以确保它不再碎片化。不过,我不会称之为优化。
找不到关于此的任何信息,但如果我找到这样的代码
fixed(Foo* foo=bar) {
doSomething(bar); // not foo
}
其中 foo 未被引用,我能否确定 bar 在该区域内保持固定并且不会因优化而消失?
是的。这就是 fixed
语句的全部要点,正如规范中所述:
For each address computed by a fixed-pointer-initializer the fixed statement ensures that the variable referenced by the address is not subject to relocation or disposal by the garbage collector for the duration of the fixed statement. For example, if the address computed by a fixed-pointer-initializer references a field of an object or an element of an array instance, the fixed statement guarantees that the containing object instance is not relocated or disposed of during the lifetime of the statement.
在你的例子中,fixed-pointer-initializer 是 bar
。但是,出于语法原因,需要声明 foo
。这可能就是这个成语的原因,其中数组 bar
必须是不可移动的,但你并不真的需要指针。
附带说明:在这样的 fixed
语句之外,可以将 bar
移出它的内存位置并不是优化。这是垃圾收集器压缩堆以确保它不再碎片化。不过,我不会称之为优化。