假设我有一个大型列表,其中每个项目都被处理一次,然后在长时间操作期间再也没有看过:
List<T> items;
// ... some stuff is done with the list then finally
for(int i = 0; i < items.Count; i++)
{
SomeOperation(items[i]);
//items[i] never used again at this point
// say i do this:
// items[i] = null;
}
Run Code Online (Sandbox Code Playgroud)
如果我取消注释items[i] = null,这会将对象解压缩到索引i并使其可用于垃圾收集吗?
从内存使用的角度来看,这样做是否会更有效率,而不是让GC在以后未使用整个列表时发生.
这忽略了一些问题,比如稍后更改代码,事实证明这些项目是在以后使用的,而且是意外的null wreck havoc.
我的同事在.NET 4.0中使用LINQ to SQL进行更复杂的查询时出错,但在更简单的情况下似乎很容易重现.考虑一个名为TransferJob的表,其中包含合成ID和位字段.
如果我们进行以下查询
using (var ctx = DBDataContext.Create())
{
var withOutConstant = ctx.TransferJobs.Select(x => new { Id = x.TransferJobID, IsAuto = x.IsFromAutoRebalance });
var withConstant = ctx.TransferJobs.Select(x => new { Id = x.TransferJobID, IsAuto = true });//note we're putting a constant value in this one
var typeA = withOutConstant.GetType();
var typeB = withConstant.GetType();
bool same = typeA == typeB; //this is true!
var together = withOutConstant.Concat(withConstant);
var realized = together.ToList();//invalid cast exception
}
Run Code Online (Sandbox Code Playgroud)
注意到抛出了无效的强制转换异常.但奇怪的是,在调试器中查看时,我们有类型相等.
只需将第二行更改为最后一行即可从IQueryable转换为使用linq转换为对象
var together = …Run Code Online (Sandbox Code Playgroud)