• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

static method or static block

 
Ranch Hand
Posts: 230
IntelliJ IDE Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Which is more efficient static block or static method ?
 
Greenhorn
Posts: 15
Android Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Depends on your particular use case. The static block is executed when the class is statically initialized (probably on the startup of your app), whereas the static method is just called when you call it in the code: http://www.jusfortechies.com/java/core-java/static-blocks.php
 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
static block may contains method call, in this case i dont worry whether we should go for static block or method .
 
Author and all-around good cowpoke
Posts: 13078
6
  • Likes 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In either case, do NOT pursue hypothetical "efficiency" at the cost of clarity and maintainability of code.

Bill
 
Bartender
Posts: 10780
71
Hibernate Eclipse IDE Ubuntu
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Santosh Kumar Nayak wrote:Which is more efficient static block or static method ?


The question is meaningless, since both things serve different purposes. And I'll go even further than William (and I'm sorry if it sounds harsh): if you're still at the stage of asking this sort of question, then you are NOT ready to be even thinking about efficiency. Even many experienced programmers get it wrong when they do.

Get your code right. Then, if you need to (and ONLY if you need to), make it fast.

Winston
 
Santosh Kumar Nayak
Ranch Hand
Posts: 230
IntelliJ IDE Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I faced this as a Interview Question hence I wanted to have a clear vision on the same.
 
Winston Gutkowski
Bartender
Posts: 10780
71
Hibernate Eclipse IDE Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Santosh Kumar Nayak wrote:I faced this as a Interview Question hence I wanted to have a clear vision on the same.


Oh dear. Another victim of a ridiculous interview question. Don't worry, it's not your fault.

All I can say is that if you didn't get the job because you couldn't answer that question, you probably didn't want to work there to begin with. It really is a ludicrous question to ask in a Java context; and I suspect very strongly that the answer could be different depending on the JVM in question.

Winston
 
Rancher
Posts: 1090
14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Another ridiculous ( I think so, with due respect to whoever asked me that question for whatever reason ) question I faced - 'which thread scheduling algorithm does the JVM use?' More than 'which scheduling algorithm', it was 'the JVM' that I couldn't understand. What are these people really testing. That we know JVM is platform dependent? That there is no 'the JVM'? That thread scheduling algorithm is an implementation detail and it may depend more on the underlying OS and how the OS works with the JVM?
 
Chan Ag
Rancher
Posts: 1090
14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Oh another one - 'what is the difference between the equals and the hashCode method?' Seriously. You won't believe it was really a sought after organization ( my personal opinion ) to work for.
 
Ranch Hand
Posts: 69
2
Netbeans IDE C++ Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Academic questions like this are good opportunities to get to know your tools better. I like to know how things work under the hood before blindly using features, myself.

This small test was conducted using JDK 1.7.0_40 using the javap utility included in the JDK.

First, lets look at using static initialization blocks



Next, using an explicit method call 'init'


As the bytecode shows, it's nearly the same doing it both ways.

The only differences that I can tell off-hand are:
1) The class contract is smaller and cleaner when using a static block.
2) With a static block, users of your class can't misuse initialization by calling init more than once (unless they reload the class using the instrumentation API!)

3) The 'init' method allows you to initialize when and on what thread you want without worrying about classloaders.

4) Might want to take a peek at what JIT does to the bytecode - I might suspect that static blocks are subject to an optimization, but don't have any evidence to support this claim *yet*.

While simple cases like this seem fairly dumb, imagine a potentially long-running static initialization process (IE constructing a giant lookup table). Having both methods available let you determine when to take the time to initialize (possibly in a background thread to shorten application start-up times).

A good question! Hopefully this little test gives you a little more insight and satisfies your *professional curiosity* (which seems to be lacking in this thread based on many of the other replies).

As a final note, here's what I feel is the order of importance when designing a solution (note, I almost exclusively write library code).

1) Public API - before writing any code 'that works', be sure your public interface is well designed, otherwise using the solution will be painful for others using your work
2) Write (good, quality) code that meets the contract of your interface (this gets easier as you know more about the standard classes and the virtual machine implementation that you're working with)
3) Before optimizing, try an ahead of time compiler (if the situation allows for it) just to check whether or not it'll boost you enough to even need to optimize
4) Optimize at the expense of your good, quality code
 
Chan Ag
Rancher
Posts: 1090
14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
With due respect to whatever you've said and demonstrated, aren't we forgetting one thing here. static methods and static blocks serve two different purposes and they are very different in how they function. So you can't really compare them cause you can't ( shouldn't ) swap one for the other whenever you please. Such comparisons hold if everything associated with two options is same and you have to choose one. I mean static methods are class methods that can be invoked more than once and static blocks are an initialization construct ( something that should happen only once ). They are different things and how can we say one yields better performance than the other when we can't ( considering it's a properly designed application ) swap one for the other.

Also initialization and a later assignment are two different things.

And I believe a static void init(){} is a bad design choice to do just an x=4.

Let me know if you have a different view ( I am just trying to process what you've said and I still don't understand how we can compare static blocks and static methods on performance when they are used differently and in different contexts ).

And I understand I could be wrong. So I'd love to hear your views and change mine in the process, if I'm wrong.


Edit : I mean 'a static void init(){} is a bad design choice to do just an x=4' if it is an initialization thing, not a reassignment.
 
Chan Ag
Rancher
Posts: 1090
14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

satisfies your *professional curiosity* (which seems to be lacking in this thread based on many of the other replies).



I think in your attempt to prove that static blocks and static methods could be compared on performance and this could be a criterion to use one for the other, you have forgotten that they were made to do different things.
 
Winston Gutkowski
Bartender
Posts: 10780
71
Hibernate Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Luke Leber wrote:Academic questions like this are good opportunities to get to know your tools better. I like to know how things work under the hood before blindly using features, myself.


Luke: First of all - a warm welcome to JavaRanch

Second: I applaud your efforts to show Santosh how the two techniques differ. I still say, however, that it's a ludicrous interview question; and something that beginners (and this is, primarily, a site for "greenhorns") really shouldn't be wasting their time on.

I also don't see any evidence from your findings that shows me that either technique would differ by anything more than nanoseconds, so choosing one over the other comes under heading of "micro-optimization" to me; something that we spend a lot of time on these forums urging people to avoid.

This small test was conducted using JDK 1.7.0_40 using the javap utility included in the JDK.


And so is only conclusive for that setup. I'm quite prepared to believe it would be similar on other versions/JVMs though.

While simple cases like this seem fairly dumb, imagine a potentially long-running static initialization process (IE constructing a giant lookup table).


Which is basically what static blocks are for (which is why they're often referred to as static 'initializers') - eager initialization that cannot be performed with a simple assignment.

Having both methods available let you determine when to take the time to initialize (possibly in a background thread to shorten application start-up times).


Indeed, if you have both methods, the static block can simply call the static method, which saves on code duplication.

1) Public API - before writing any code 'that works', be sure your public interface is well designed, otherwise using the solution will be painful for others using your work


And on this point, there is something else to remember: You can't easily document a static block.

3) Before optimizing, try an ahead of time compiler (if the situation allows for it) just to check whether or not it'll boost you enough to even need to optimize


And there we disagree. Assuming that your code is correct and well-designed, you should never optimize unless there is a provable need to do so. All the other things you mention only come into play after that condition has been met; and I'm afraid that nothing you've shown us would lead me to believe that there is any condition under which you would choose one of the stated methods over the other for reasons of speed.

A good question! Hopefully this little test gives you a little more insight and satisfies your *professional curiosity* (which seems to be lacking in this thread based on many of the other replies).


Again, I have to disagree. In the stated context (an interview), it's an awful question; and I certainly wouldn't want to work for a company that values knowledge I would put under the heading of 'Java trivia'. I simply can't see any situation in which a "professional" would gain from knowing something like this.

Idle curiosity, on the other hand, is another thing; and I'm all in favour of people finding out anything they want about whatever "yanks their chain"...but not at the expense of more important things - of which there are plenty.

To me, this comes under the same heading as questions about where and how Java structures memory and puts variables - interesting to some maybe, and possibly of use to someone writing a JVM or a better garbage-collector, but simply not important to someone trying to use the language. And moreover, probably a distraction.

Winston
 
Bartender
Posts: 1051
5
Hibernate Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Chan Ag wrote:
Oh another one - 'what is the difference between the equals and the hashCode method?' Seriously. You won't believe it was really a sought after organization ( my personal opinion ) to work for.


I don't think is an unreasonable interview question. It is the sort of question that filters out those who know some core Java and those who have be asked to tinker with a few web technologies for a year or two.
 
Chan Ag
Rancher
Posts: 1090
14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
James Boswell,

I'd love to correct myself/ or be corrected by others. I did answer this question in a certain way and it worked. But I'd like to know how such questions should be answered. They have differences that apply to a specific context. If an interviewer is asking such differences, I think it is imperative they also mention the context cause otherwise I don't see how someone can answer it in a short period of time.

And what's with 'who know some core Java and those who have be asked to tinker with a few web technologies for a year or two'? May be I am one of those cause I can only relate core java things to equals and hashCode. They behave differently if you're working on web technologies?

Winston,

Thanks. You've made some very nice points in an easy to understand language and they've helped me see a couple of things. I have a question, not with your points, but with such interview questions. If the question is just which of the two is better, do you think somebody should think so much about lazy and eager initializations and answer the question. Aren't they very specific contexts ( and we must also not forget the class hierarchy implications here - in a way aren't we changing the design when we change a static block to call a static method from the static block. I remember reading about the static blocks in JLS. Isn't it correct that in many cases, this change could make the code behave differently, more so in multi-threaded environments? ). I mean if they explained the initialization is expensive, may be the interviewee would suggest how to go about it. But asking which of the two is better without mentioning the context does not make sense to me.



 
James Boswell
Bartender
Posts: 1051
5
Hibernate Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Chan Ag wrote:And what's with 'who know some core Java and those who have be asked to tinker with a few web technologies for a year or two'? May be I am one of those cause I can only relate core java things to equals and hashCode. They behave differently if you're working on web technologies?


Chan

Some developers move over to Java from a different language (say C++) and due to project commitments, they are put straight into a JEE role. What can happen in such scenarios is that the developer gets shielded from the core/basics of the language (e.g. the meaning of hashCode and equals). That is why I think it is not an unreasonable interview question. It is testing your knowledge of core Java, rather than the vast number of web technologies.
 
Chan Ag
Rancher
Posts: 1090
14
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
All I'm saying is this.

An equals returns a boolean and a hashCode returns an int. They are not even overloaded methods. Both are in the Object class and there is a contract that binds them together and hence places some requirements on how they are to be overridden/used. If somebody asked how equals and hashCode work together, I understand what they're asking. But what would you say when they are asking what are the differences between the two. Everything about those two methods is different; it's just that they work together in a certain way and in a certain context and there is a contract ( which is not even enforced by the compiler but should be maintained if you want the code to behave correctly ) that binds them together.

Also we all like to think and take questions well. But like we are expected to give a reasonable answer, isn't the question also supposed to be properly framed?
 
James Boswell
Bartender
Posts: 1051
5
Hibernate Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Chan

I agree, perhaps the question could be phrased better but if you know the purpose of each method, you should be able to answer it.
 
Winston Gutkowski
Bartender
Posts: 10780
71
Hibernate Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Chan Ag wrote:I have a question, not with your points, but with such interview questions. If the question is just which of the two is better, do you think somebody should think so much about lazy and eager initializations and answer the question.


In the specific case of the question posed by Santosh, I'd say probably not. In fact, in an interview situation, I'd be very careful not to answer questions you weren't asked, and nobody's really mentioned the old lazy vs. eager debate.

Aren't they very specific contexts ( and we must also not forget the class hierarchy implications here - in a way aren't we changing the design when we change a static block to call a static method from the static block.
I remember reading about the static blocks in JLS. Isn't it correct that in many cases, this change could make the code behave differently, more so in multi-threaded environments? ).


TBH, I hadn't thought about it; but you're probably right. That certainly isn't a reason not to do it though - code normalization is why we have methods, after all - and you could certainly ensure that the code works correctly in multi-threaded situations either way. And the very fact that we're only even considering the issue when initialization is expensive probably makes the cost of synchronization trivial.

My 2¢.

Winston
 
Chan Ag
Rancher
Posts: 1090
14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks, Winston.
 
Luke Leber
Ranch Hand
Posts: 69
2
Netbeans IDE C++ Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Winston Gutkowski wrote:

I also don't see any evidence from your findings that shows me that either technique would differ by anything more than nanoseconds


I don't recall saying anything about performance differences at all. In fact, I would be very surprised to find a notable difference in any context between the two techniques. If anything, the little absurd test shows that the only difference seems to be when the bytecode is ran. I've re-read this topic twice now without finding a concrete answer and simply provided one with hard evidence to back it up. To me, "Don't worry about it" is not a valid answer.

Winston Gutkowski wrote:

1) Public API - before writing any code 'that works', be sure your public interface is well designed, otherwise using the solution will be painful for others using your work


And on this point, there is something else to remember: You can't easily document a static block.



I feel that if internal static initialization blocks need to have public documentation, the design is flat out wrong for using static initialization blocks. Once you force the user to know your internals, the design is flawed beyond repair.

Winston Gutkowski wrote:

Luke Leber wrote:3) Before optimizing, try an ahead of time compiler (if the situation allows for it) just to check whether or not it'll boost you enough to even need to optimize


And there we disagree. Assuming that your code is correct and well-designed, you should never optimize unless there is a provable need to do so. All the other things you mention only come into play after that condition has been met; and I'm afraid that nothing you've shown us would lead me to believe that there is any condition under which you would choose one of the stated methods over the other for reasons of speed.



Whoa there, we're not optimizing anything until we absolutely need to (I thought that was obvious from the numbered steps). If optimization is required, I would rather run benchmarks after applying an AOT compilation rather than optimizing the code by hand.


I still think that the correct answer to this question is not that no comparison can be made between apples and oranges, but rather that there is no real performance difference between static initializer blocks and static initialization methods (provided each run exactly 1 time using similar system resources).

I would be very pleased if someone could provide a counter-example to suggest otherwise, or any reason that a comparison between the two techniques (again, provided each is ran exactly once) is invalid (other than the "intended uses" argument - which is just semantics anyway).

Hope to hear back soon.

Seems I've butchered quote tags.

Seems I've finally fixed them
 
Sheriff
Posts: 28411
102
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Luke Leber wrote:I still think that the correct answer to this question is not that no comparison can be made between apples and oranges, but rather that there is no real performance difference between static initializer blocks and static initialization methods (provided each run exactly 1 time using similar system resources).



I would agree with that. However to pick a small nit -- the original post asked about "efficiency" rather than "performance difference". Choosing a static initializer block rather than a static initialization method means, as I believe you already pointed out, that you don't have to document the code. That makes it more efficient -- for some definition of efficient -- because the programmer doesn't have to spend any time understanding the feature.
 
Winston Gutkowski
Bartender
Posts: 10780
71
Hibernate Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Luke Leber wrote:I've re-read this topic twice now without finding a concrete answer and simply provided one with hard evidence to back it up. To me, "Don't worry about it" is not a valid answer.


Then we'll have to agree to disagree. I'd say that in the the context of both this question and this website it's often the best answer you can give. People come here because they want to learn, and part of our task (IMO) is to steer them away from obsessing about things that just don't matter. I have never once, in 12 years of writing Java, worried about whether I was going to use a static block or a static method, or the relative efficiencies (which was the original question) of the two approaches.

Your style is plainly different, and I have no problem with it; but I'm afraid I won't be including proofs with my advice anytime soon.

Winston
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic