为什么安卓preFER静态类静态、preFER

由网友(放纵旳爱情╮)分享简介:我看到了很多的Java code其中安卓prefers让开发人员使用静态内部类。特别是对于像ViewHolder格式定制ListAdapters。I see a lot of java code where android prefers to have developers use static inner cla...

我看到了很多的Java code其中安卓prefers让开发人员使用静态内部类。特别是对于像ViewHolder格式定制ListAdapters。

I see a lot of java code where android prefers to have developers use static inner classes. Particularly for patterns like the ViewHolder Pattern in custom ListAdapters.

我不知道的区别是静态的和非静态类的东西。我读过有关,但它似乎并没有在其性能和内存占用关注是有道理的。

I'm not sure what the differences are between static and non-static classes. I've read about it but it doesn't seem to make sense when concerned with performance or memory-footprint.

推荐答案

这不只是Android开发者...

It's not just Android developers...

一个非静态内部类始终保持一个隐含的引用封闭对象。如果你不需要的参考,它是所有成本内存。试想一下:

A non-static inner class always keeps an implicit reference to the enclosing object. If you don't need that reference, all it does is cost memory. Consider this:

class Outer {
    class NonStaticInner {}
    static class StaticInner {}
    public List<Object> foo(){ 
        return Arrays.asList(
            new NonStaticInner(),
            new StaticInner()); 
    }
}

当你编译它,你得到的将是这样的:

When you compile it, what you get will be something like this:

class Outer {
    Outer(){}
    public List<Object> foo(){ 
        return Arrays.asList(
            new Outer$NonStaticInner(this),
            new StaticInner()); 
    }
}
class Outer$NonStaticInner {
    private final Outer this$0;
    Outer$NonStaticInner(Outer enclosing) { this$0 = enclosing; }
}
class Outer$StaticInner {
    Outer$StaticInner(){}
}
阅读全文

相关推荐

最新文章