哪种方法消耗更多资源:静态还是 getter/setter?
特别是在 J2ME 中,哪种方法消耗更多资源:操作公共静态变量或操作 set() 和 get() 方法?
Particularly in J2ME which approach consumes more resource : manipulating the public static
variables or manipulating the set()
and get()
methods ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是不可能的,因为这取决于实际的运行环境。 JIT、AOT 或 Hotspot 编译器可以很好地优化掉潜在的方法开销。
That's impossible to tell, since it depends on the actual runtime environment. A JIT, AOT or Hotspot compiler may very well optimize away the potential method overhead.
引入访问器方法会显着增加类文件的大小。然而:
Introducing accessor methods significantly increases the size of class files. However:
使用
get()
和set()
方法可能比直接访问属性的成本更高一些(尽管编译器或 JIT 可以通过内联方法调用来优化它们)但无论如何,差异可以忽略不计。另外,一般来说,您不应将所有属性声明为静态
,而仅声明常量值。另一方面,使用
get()
和set()
方法是强制数据封装的首选方法,这是一种很好的面向对象编程实践。如果没有这些方法,就会迫使您将属性暴露给外部,从而削弱类隐藏实现细节的能力,并使将来对实现进行更改变得更加困难。Using
get()
andset()
methods may be a bit more costly than directly accessing attributes, (although the compiler or the JIT my optimize the method calls by inlining them) but anyway the difference is negligible. Also, in general you should not declare all your attributes asstatic
, only the constant values.On the other hand, using
get()
andset()
methods is the the preferred option for enforcing the encapsulation of data, it's a good object-oriented programming practice. Not having those methods, forces you to expose the attributes to the outside, diminishing the ability of the class to hide implementation details and making future changes in the implementation harder.public static
字段访问比setter / getter
方法消耗的资源更少。如果您使用的是现代热点 JVM,则差异很小。public static
field access would cost you less resources thansetter / getter
methods. If you are on a modern hotspot JVM, there will be minimal difference.set 和 get 比访问普通字段消耗更多。您可能不是指
静态
。set and get consume more than access to normal fields. You probably did not mean
static
.