构造函数中的所有代码或构造函数中的使用方法 [英] All codes in constructor or using methods in constructor

查看:114
本文介绍了构造函数中的所有代码或构造函数中的使用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,

我是编程的新手.我正在从加载时间,内存使用情况等方面考虑Java程序的性能.

哪种编程风格将提供更好的性能:

a)将每一行代码放入构造函数中,例如:

Hello,

I''m a newbie in programming. I''m thinking about the performance of a java program in terms of its load time,memory usage etc.

Which programming style will give better performance:

a) put every line of code into constructor for example :

Class abc 
{
   -component declarations-
  
   abc() //constructor
  {

    -all the codes line by line-
  }
}



b)因为我希望代码看起来更有条理,所以我创建了要在
中调用的方法 构造函数,例如:



b) As I want my code to look more organized, I create methods to be called in the
constructor for example:

Class abc
{
   -component declarations-

   abc() //constructor
  {
    method1();
    method2();

  }
}



我通过在主函数中创建对象来运行程序.
那么哪个会带来更好的性能呢?


Thx提供任何帮助和指导^.^



I run the program by creating the object in the main function.
So which one will give better performance?


Thx for any help and guidance ^.^

推荐答案

始终以使代码最易于维护的方式提供代码,同时仍提供所有必要的功能.如果将所有代码放入构造函数中,切勿创建意粉代码.
Always code in the way that will make code the most maintainable while still providing all the necessary functionality. Never create spaghetti code which is what you will get if you put all your code in the constructor.


我真的不认为这两个性能"上的区别方法"."

无论如何,似乎您正在执行顺序编码,我并不是说您不应该这样做,但是,如果您要学习的话,也许可以看看多层体系结构

I really don''t think there''s a "performance" difference between these two "methods"."

Anyway, it seems you''re doing sequential coding, I''m not saying you shouldn''t, but if you''re trying to learn you maybe look into Object-oriented programming and Multitier architecture

That might be a good start.


显然,样式(b)涉及两个函数调用(传递参数和分配局部变量)的开销,并且可能为编译器提供较少的全局优化机会. br/>
实际上,这种开销通常可以忽略不计.

实际上,真正重要的是为可读性和可维护性实现正确的代码结构.

如果method1和method2从未在构造函数之外的地方使用过,也永远不会在其他地方使用,那么您可以质疑创建它们的好处,除了保持较小的功能之外.

另外,您也可以将代码块放在本地块{}中.
Obviously style (b) involves the overhead of two function calls (passing arguments and allocating local variables) and might give the compiler less opportunities for global optimizations.

In practice this overhead is often neglectable.

What really matters is indeed to achieve a correct structuring of your code for readability and maintenability.

If method1 and method2 are never used elsewhere than in the constructor and will never be, you can question the benefit to create them, except for the sake of keeping small functions.

Alternatively, you could just enclose the chunks of code in a local block {}.


这篇关于构造函数中的所有代码或构造函数中的使用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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