开发者

Can value types be implemented by inlining?

When I first saw the value types in C#, the first thing I thought was "wow, what a great optimization", the second thing is, "do we really need a new language construct? can't we do that with annotations instead?".

The idea is, given a class, we'll use it as we always did

class A {int i;}
class B {
    A m_a;
    int F(A a) {m_a = a;}
}

On a whim we'll change A to be

[ValueType]
class A {int i;int j;}

And the compiler will automatically convert class B to be

class B {
#region A
    int A_i;
    int A_j;
#开发者_开发知识库endregion
int F(/*A param*/int i,int j) {
#region A_assign
    A_i = i;
    A_j = j;
#endregion
}

Bear in mind, that if the compiler doesn't wish to optimize some instance - it doesn't have to. It would work either way.

It might arise problems with templates,

int f<T>() {
    T t; // how much stack should I allocate
}

but I'm not sure it's much worse than the current situation. I'm actually not sure what happens now (is f<struct_of_100_bytes> a different function than f<int>?).


Now imagine inheritance. Or arrays. Or arguments. Or generics. Or implementing an interface. Or assigning to object/dynamic.

And keep in mind that the runtime supports multiple compilers.

Having a specific keyword (struct) rather than an attribute is not really a big change (indeed, in terms of the CLI everything is called a class), but the overall situation is much more complex than your example.

Basically, struct does pretty-much everything you mention, and works in all the scenarios listed. Since it generally (for locals) uses the stack, it already behaves much like you describe.

Re the "separate function" question; firstly, generics are not "templates" (it is runtime vs compile-time). But generics get a JIT per value-type, and a single JIT per reference-type (because indeed: the stack layout changes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜