选择何时实例化类 [英] Choosing when to instantiate classes

查看:36
本文介绍了选择何时实例化类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近为一个作业编写了一个类,其中我必须将名称存储在 ArrayList 中(在 Java 中).我将 ArrayList 初始化为实例变量 private ArrayList名称.后来当我根据解决方案检查我的工作时,我注意到他们已经在 run() 方法中初始化了他们的 ArrayList.

I recently wrote a class for an assignment in which I had to store names in an ArrayList (in java). I initialized the ArrayList as an instance variable private ArrayList<String> names. Later when I checked my work against the solution, I noticed that they had initialized their ArrayList in the run() method instead.

我想了一会儿,我觉得这可能是一个品味问题,但一般来说,在这种情况下人们会如何选择?是占用更少的内存还是什么?

I thought about this for a bit and I kind of feel it might be a matter of taste, but in general how does one choose in situations like this? Does one take up less memory or something?

PS 我喜欢 Ruby 中以 @ 符号开头的实例变量:它们更可爱.

PS I like the instance variables in Ruby that start with an @ symbol: they are lovelier.

(元问题:这个问题的标题是什么?)

(meta-question: What would be a better title for this question?)

推荐答案

用伟大的 Knuth 的话来说过早的优化是万恶之源".

In the words of the great Knuth "Premature optimization is the root of all evil".

只需担心您的程序是否正常运行并且没有错误.这比以后难以调试的模糊优化重要得多.

Just worry that your program functions correctly and that it does not have bugs. This is far more important than an obscure optimization that will be hard to debug later on.

但是要回答你的问题——如果你在类成员中初始化,内存将在第一次在代码中提到你的类时分配(即当你调用它的方法时).如果在方法中初始化,则在调用此特定方法时会稍后进行内存分配.

But to answer your question - if you initialize in the class member, the memory will be allocated the first time a mention of your class is done in the code (i.e. when you call a method from it). If you initialize in a method, the memory allocation occurs later, when you call this specific method.

所以只是后面初始化的问题……这在业界叫做懒惰初始化.

So it is only a question of initializing later... this is called lazy initialization in the industry.

这篇关于选择何时实例化类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆