Android 这两个代码中哪一个在内存方面更好?

Android 这两个代码中哪一个在内存方面更好?,android,for-loop,arraylist,textview,Android,For Loop,Arraylist,Textview,我在Udacity的课程中学习android开发。当我学习第2课时,出现了一种情况,我们必须创建多个文本视图,从先前创建的ArrayList字符串设置文本,并将这些文本视图添加到线性布局中 通用代码: ArrayList<String> words = new ArrayList<String>(); words.add("one"); words.add("two"); words.add("three"); words.add("fo

我在Udacity的课程中学习android开发。当我学习第2课时,出现了一种情况,我们必须创建多个文本视图,从先前创建的
ArrayList
字符串设置文本,并将这些文本视图添加到线性布局中

通用代码:

 ArrayList<String> words = new ArrayList<String>();
    words.add("one");
    words.add("two");
    words.add("three");
    words.add("four");
    words.add("five");
    words.add("six");
    words.add("seven");
    words.add("eight");
    words.add("nine");
    words.add("ten");
    LinearLayout rootView =(LinearLayout) findViewById(R.id.rootView);
ArrayList words=new ArrayList();
词语。添加(“一”);
字。加上(“两”);
字。添加(“三”);
字。加上(“四”);
字。加上(“五”);
字。添加(“六”);
字。添加(“七”);
字。添加(“八”);
字。添加(“九”);
字。加上(“十”);
LinearLayout rootView=(LinearLayout)findViewById(R.id.rootView);
现在他们做了什么:

for(int i=0;i<10;i++){
TextView wordView=new TextView(this);
wordView.setText(words.get(i));
rootView.addView(wordView);
 }

for(int i=0;i没有区别。在这两种情况下,
TextView
实例都不能被垃圾收集,因此内存足迹是相等的

因为即使在循环之后,我也有对每个文本视图的引用


如果你真的不需要这些引用,那么它只是毫无意义的。它不是内存相关的优势。

< p>你的代码看起来不错。但是我不认为有10个相同的文本视图。我会考虑使用ListVIEW或RealeVIEW,如果你把它当作一个列表,并考虑优化你的代码。


但您的代码仍然很好。

从性能角度看,这并不重要。正如您所说:

我觉得我的代码更好,因为即使在循环之后,我也有对每个TextView的引用


如果你需要它,请执行它。

<代码>我会考虑使用ListVIEW或RealReVIEW
,但是每一行都是单个TeXVIEW,所以……这将是什么样的优化?此外,除了单个行之外,还可以有一个视图组。ListVIEW被优化以显示项目列表。因此,在内存中,行被重用。
ArrayList<TextView> wordView = new ArrayList<TextView>();
    for(int i=0;i<10;i++)
    {
        wordView.add(new TextView(this));
        wordView.get(i).setText(words.get(i));
        rootView.addView(wordView.get(i));


    }