开发者

static blocks in java [closed]

It's difficult to tell what is bein开发者_如何转开发g asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 12 years ago.

why is the use of static blocks considered inefficient programming practice?


Static blocks are associated with classes, not instances. You lose whatever benefit that multiple instances, each with their own state and behavior, gives to you. If you wrote an entire application that way, it would suggest to me that an object-oriented language wasn't appropriate for you or that problem.

But with that said, there's no harm in using statics where they make sense. There's no loss of efficiency.


I am not aware of any such advice.

Overuse of static (particularly static variables) in general is an indication of poor OO design. But there are no specific performance concerns with static initialiser blocks.

If you are aware of such advice, please provide a citation / link.


Without a specific example its difficult to know but never say never..

There are definitely cases where a solution can be clearer when a small part of it is in a static block, clearly laid out at the head of the class.

However if you find yourself putting large amounts of code in there this is probably a bad code smell .

As you probably know any code in that static block gets initialised as soon as the class is loaded by the class loader. This gives you much less control about when it is loaded and potentially (if you have multiple class loaders in your system) it gets loaded more than once which may not be what you want. If you have a lot of loading going on in static blocks, rather than lazily, it can also slow the startup time of your app.


Let's say it depends on how you use it. Like everything it can be misused and be an inefficient technique to solve some problems, but yet for other things it is useful.

So you can't simply state that the use of static blocks is inefficient.


On the same topic :

  • Static Initialization Blocks.
  • Can anyone tell me that what is the use of a static block in a class?
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜