×

Discussion Board

Results 1 to 3 of 3
  1. #1
    Registered User
    Join Date
    Dec 2003
    Posts
    9

    declaring methods as final

    Is it worth from an optimization standpoint to declare all (non-instantiable) methods in the midet as final ?

    Bored coder

  2. #2
    Registered User
    Join Date
    Mar 2003
    Location
    United Kingdom
    Posts
    49
    I suspect that the compiler will take advantage of the fact that constants (final variables) will not be modified for the duration of the variables life, so a number of assumptions can be made during code optimisation. I am not a Java expert (yet), but going on my C / C++ knowledge I would say that if you have anything that is constant then declare it as final. In addition, if you have variables that are final inside classes that you are going to instantiate then you should also declare them as static. This will help save heap space, as I believe that only one copy of the variable will be held in memory, no matter how many instances you have.

  3. #3
    Registered User
    Join Date
    Mar 2003
    Location
    United Kingdom
    Posts
    49
    Hmm, sorry misread your post, you asked about methods and not variables. I have looked into final and private methods and found out some interesting facts:

    1. private methods are automatically declared as final as they cannot be overidden by sub classes
    2. Optimising compilers and JVM's can take advantage of the fact that final / private methods cannot be overriden, which means that runtime dynamic binding can be bypassed. This means that when you call your final method, the JVM does not have to search the inheritance hierarchy, thus your method can be called directly, or even inlined
    Last edited by mrmop; 2004-01-04 at 18:16.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
×