-2

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

meenakshi
  • 23
  • 1
  • 3
  • Must be a JDK 8 feature - can't wait to read up on it. (Just kidding, for those of you whose sarcasm meters need calibrating.) – duffymo Oct 17 '10 at 13:40

4 Answers4

3

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.

duffymo
  • 305,152
  • 44
  • 369
  • 561
2

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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
2

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.

shovel
  • 19
  • 4
  • thanks everyone. i did not give a specific example, coz i used a static block in my code and a senior told me not to.. was puzzled. so wanted to know. – meenakshi Oct 17 '10 at 13:55
1

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 :

Community
  • 1
  • 1
Colin Hebert
  • 91,525
  • 15
  • 160
  • 151