jos*_*uan 9 c# linq csc visual-studio
我发现使用Visual Studio开发了一个不愉快的行为.在编译C#时它挂起了我的机器.
我已经减少了对下一个最小源代码的行为
using System.Collections.Generic;
using System.Linq;
namespace memoryOverflowCsharpCompiler {
class SomeType { public decimal x; }
class TypeWrapper : Dictionary<int,
Dictionary<int,
Dictionary<int, SomeType [] []>>> {
public decimal minimumX() {
return base.Values.Min(a =>
a.Values.Min(b =>
b.Values.Min(c =>
c .Sum(d =>
d .Sum(e => e.x)))));
}
}
}
Run Code Online (Sandbox Code Playgroud)
用.编译
PROMPT> csc source.cs
*** BANG! overflow memory usage (up to ~3G)
PROMPT> csc /?
Microsoft (R) Visual C# Compiler version 12.0.30501.0
Copyright (C) Microsoft Corporation. All rights reserved.
...
Run Code Online (Sandbox Code Playgroud)
(使用Windows 8.1 Pro N x64; csc
编译器进程运行时为32位)
悦目的修改不会产生这种行为(例如,改变decimal
的int
,减少一层嵌套,...),进行大Select
则减少,做工精细
明确的解决方法:
return base.Values.SelectMany(a =>
a.Values.SelectMany(b =>
b.Values.Select (c =>
c. Sum (d =>
d. Sum (e => e.x))))).Min();
Run Code Online (Sandbox Code Playgroud)
虽然存在此显式解决方法,但不保证不会再次发生此行为.
怎么了?
谢谢!
在这种情况下,泛型类型解析似乎失败了。decimal
从到 的更改int
是偶然的。如果增加嵌套级别,您会发现 int 也会失败。在我的 x64 机器上,此代码可以编译为int
和decimal
并且使用大约 2.5GB 内存,但是当内存使用量增长到大约 4GB 时,增加嵌套级别会导致溢出。
显式指定类型参数允许编译代码:
class TypeWrapper : Dictionary<int, Dictionary<int, Dictionary<int, Dictionary<int, SomeType[][]>>>>
{
public decimal minimumX()
{
return base.Values
.Min<Dictionary<int, Dictionary<int, Dictionary<int, SomeType[][]>>>, decimal>(a => a.Values
.Min<Dictionary<int, Dictionary<int, SomeType[][]>>, decimal>(b => b.Values
.Min<Dictionary<int, SomeType[][]>, decimal>(c => c.Values
.Min(d => d
.Sum(e => e.Sum(f => f.x))
)
)
)
);
}
}
Run Code Online (Sandbox Code Playgroud)
当您通过引入局部变量来减少嵌套时,编译器也可以工作:
class TypeWrapper : Dictionary<int, Dictionary<int, Dictionary<int, Dictionary<int, SomeType[][]>>>>
{
public decimal minimumX()
{
Func<Dictionary<int, SomeType[][]>, decimal> inner = (Dictionary<int, SomeType[][]> c) => c.Values
.Min(d => d
.Sum(e => e.Sum(f => f.x))
);
return base.Values
.Min(a => a.Values
.Min(b => b.Values
.Min(inner)
)
);
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
317 次 |
最近记录: |