Java Code Small Detail Note __ Code

Source: Internet
Author: User

One, avoid multiple return (exit point)

According to your method, make sure there is only one exit point. Do not use returns in the same place or in more than one place. For example, the following code, notrecommended(not recommended), is because there are multiple exit points (the return statement).

    Private Boolean iseligible (int age) {  
      if [age >] {return  
        true;  
      } else{return  
        false;  
      }  
    
The following code has been upgraded, and this is the later version.
<pre name= "code" class= "Java" >    private boolean iseligible (int age) {  
      Boolean result;  
      if (age > +) {result  
        = true;  
      } else{result  
        = false;  
      }  
      return result;  
    
Two Simplify If-else
I've written a few practical methods as a reference, checking statement conditions and returning a value based on that condition. For example, consider the Iseligible method, as you have seen before:
<pre name= "code" class= "Java" >    private boolean iseligible (int age) {  
      Boolean result;  
      if (age > +) {result  
        = true;  
      } else{result  
        = false;  
      }  
      return result;  
    
The entire method is rewritten with a single return statement:
<pre name= "code" class= "Java" >    private boolean iseligible (int age) {return age  
     
    > 18;  
     
    
Note that the following programming process can improve the ability of the system.
<p><strong>1. As far as possible in the appropriate situation to use a single case </strong></p><p> use a single example can reduce the burden of loading, shorten the loading time, improve the load efficiency, However, not all places are applicable to the single example, in simple terms, the single case is mainly used in the following three aspects of:</p><ul> <li> control resources, through thread synchronization to control the concurrent access of resources;</li> <li> Control instances to achieve the goal of saving resources;</li> <li> control data sharing, without establishing a direct association, to enable multiple unrelated processes or threads to communicate between. </li></ul><p><strong>2. Try to avoid using static variables </strong></p><p> you know, When an object is defined as a STATAIC variable, the GC usually does not reclaim the memory that the object occupies, such as </p><p>public class a{static B = new B (); At this point, the life cycle of static variable B is synchronized with Class A, and if Class A does not unload, then the B object will reside in memory until the program terminates. </p><p><strong>3. Try to avoid too many too often create Java objects </strong></p><p> try to avoid the new object in the frequently invoked method, loop, Because the system not only takes time to create objects, but also takes time to garbage collection and processing of these objects, we can control the maximum reuse of objects, preferably with a basic data type or array to replace the object. </p><p><strong>4. The use of the final modifier </strong></p><p> class with the final modifier is not derived. In the Java Core API, there are many examples of final application, such as java.lang.String. Specify final to prevent the user from overwriting the length () method for the string class. In addition, if a class is final, all methods of that class are final. The Java compiler looks for the opportunity to inline (inline) all final methods (this is related to the specific compiler implementation). This will increase performance by an average of 50%. </p><p><strong>5. Try to use local variables </strong></p><p> The parameters passed when the method is invoked and the temporary variables created in the call are saved in the stack (stack) faster. Other variables, such as static variables, instance variables, and so on, are created in the heap (Heap) in a slower speed. </p><p><strong>6. As far as possible to deal with the types of packaging and basic types of use sites </strong></p><p> Although the wrapper type and base type can be converted to each other during use, the memory areas produced by both are completely different, the base type data generation and processing are processed on the stack, the wrapper type is an object, and an instance is generated in the heap. </p><p> in the collection class object, there are objects that need to be handled by the wrapper type, and other processes advocate the use of the base type. </p><p><strong>7. Use synchronized carefully, minimize the Synchronize method </strong></p><p> know, To achieve synchronization is a very large system overhead as a cost, and may even cause deadlock, so try to avoid unnecessary synchronization control. When the Synchronize method is invoked, the current object is locked directly, and other threads cannot invoke other methods of the current object until the method has been executed. So the Synchronize method is as small as possible, and should try to use method synchronization instead of code block synchronization. </p><p><strong>8. Try to use StringBuilder and StringBuffer for string concatenation </strong></p><p> I don't have much to say about that. </p><p><strong>9. Try not to use the Finalize method </strong></p><p> in fact, It's a bad choice to put resource cleanup in the Finalize method, because the GC is a lot of work, especially when it comes to recovering young generation memory, which mostly causes applications to pause, so choosing a Finalize method for resource cleanup can result in a greater GC burden and less efficient program performance. </p><p><strong>10. Use basic data types as much as possible instead of objects </strong></p><p>string str = "Hello"; The above method creates a "Hello" string, and the JVM's character cache pool caches the string, </p><p>string str = new string ("Hello"), and the program, in addition to creating a string, STR refers to a string object that contains a char[] array at the bottom, and the char[] array, in turn, holds the h,e,l,l,o</p><p><strong>11. A single thread should try to use HashMap, Arraylist</strong></p><p>hashtable, vector and so on use the synchronization mechanism, reduces the performance. </p><p><strong>12. Create hashmap</strong></p><p> as reasonably as possible when you want to create a larger hashmap, To make full use of another constructor public HashMap (int initialcapacity, float loadfactor) to avoid HashMap multiple hash refactoring, scaling is a very performance-intensive thing, In the default initialcapacity only 16, and Loadfactor is 0.75, how much capacity you need, you'd better accurately estimate the best size you need, the same hashtable,vectors is the same reason. </p><p> #p #</p><p><strong>13. Minimizing repetitive calculations of variables  </strong></p><p> such as </p><p>for (int i=0;i<list.size (); i++) should be changed to </p><p>for (int i=0,len=list.size (); I<len i++) and should avoid the use of complex expressions in loops in which cyclic conditions are computed repeatedly, and the program will run faster if the value of the loop is not changed without using complex expressions. </p><p><strong>14. Try to avoid unnecessary creation </strong></p><p> such as </p><p>a a = new A (); if (i==1) {list.add (a);} Should be changed to </p><p>if (I==1) {A A = new A (); List.add (a);} </p><p><strong>15. Try to release resources in finally blocks </strong></p><p> the resources used in the program should be freed to avoid resource leaks. It's better to do it in the finally block. The finally block is always executed, regardless of the outcome of the program execution, to ensure that the resource is properly closed. </p><p><strong>16. Use shift instead of ' A/b ' Operation </strong></p><p> '/' is a very expensive operation, Using shift operations will be faster and more efficient </p><p> such as </p><p>int num = A/4; int num = A/8; should be changed to </p><p>int num = a "2;" int num = a 3; Note that the use of shift should add comments, because the shift operation is not intuitive, more difficult to understand. </p><p><strong>17. Use shifts instead of ' a*b ' operations </strong></p><p> the same, for ' * ' operations, Using shift operations will be faster and more efficient </p><p> such as </p><p>int num = a * 4; int num = A * 8; should be changed to </p><p>int num = a "2"; int num = a 3;</p><p><strong>18. Try to determine stringbuffer capacity </strong></p><p> The StringBuffer constructor creates a character array of the default size (usually 16). In use, if this size is exceeded, the memory is reassigned, a larger array is created, the original array is copied, and the old array is discarded. In most cases, you can createThe size is specified when the StringBuffer is built, thus avoiding automatic growth when capacity is not sufficient to improve performance. </p><p> such as: </p><p>stringbuffer buffer = new StringBuffer (1000);</p><p> < Strong>19. To release a reference to a useless object as early as possible </strong></p><p> most of the time, the object referenced by the method local reference variable becomes garbage as the method ends, so most of the time the program does not need to be partial, The reference variable is explicitly set to null.</p><p> for example: </p><p>public void Test () {Object obj = new Object (); Obj=null; This is not necessary, and as the execution of Method test () completes, the scope of the OBJ reference variable in the program ends. But if it is changed to the following: </p><p>public void Test () {Object obj = new Object (); obj=null;//perform time-consuming, memory-intensive operations, or invoke time-consuming, memory-consuming methods ...} It is necessary at this point to assign obj to null and to release the reference to object objects as soon as possible. </p><p><strong>20. Try to avoid using two-dimensional arrays </strong></p><p> two-dimensional data to occupy more memory space than a one-dimensional array, about 10 times times more. </p><p><strong>21. Try to avoid using split</strong></p><p> unless it is necessary, or avoid using split, Split because of the support of regular expressions, so inefficient, if the frequent dozens of, millions of of the call will consume a lot of resources, if you do need frequent call split, you can consider the use of Apache Stringutils.split (String,char), Frequent split can cache the results. </p><p><strong>22.arraylist&linkedlist</strong></p><p> one is a linear table, one is linked list, in a word, random query as far as possible to use arraylist,arraylist better than linkedlist,linkedlist also move the pointer, Add delete operation LinkedList better than arraylist,arraylist also move data, but this is theoretical analysis, the fact is not so, it is important to understand the data structure of 2, the right remedy. </p><p><strong>23. Try to use System.arraycopy () instead of iterating through the array </strong></p><p> System.arraycopy () is much faster than replicating an array by looping. </p><p><strong>24. Cache frequently used objects </strong></p><p> cache objects as often as possible, using arrays, or HashMap containers for caching, but this approach may cause the system to take up too much cache, performance degradation, recommend the use of some third-party open source tools, such as Ehcache,oscache cache, they basically implement the Fifo/flu cache algorithm. </p><p><strong>25. Try to avoid very large memory allocations </strong></p><p> Sometimes the problem is not caused by the state of the heap, It is due to the allocation failure. The allocated memory blocks must be contiguous, and as the heap becomes more and more full, it becomes increasingly difficult to find larger contiguous blocks. </p><p><strong>26. Use exceptions </strong></p><p> when creating an exception, you need to collect a stack trace (stack track), This stack trace is used to describe where the exception was created. Building these stack traces requires a snapshot of the runtime stack, and that's a huge part of the overhead. When you need to create a exception, the JVM has to say: "Don't move, I want to save a snapshot of what you are like, so temporarily stop the stack and the stack operation." The stack trace contains not only one or two elements in the runtime stack, but each element of the stack. </p><p> If you create a exception, you have to pay the price. Fortunately, the catch exception is not expensive, so you can use Try-catch to wrap up the core content. Technically speaking, you can evenThrow the exception at random without paying a great price. It is not throw operations that incur performance losses (although it is somewhat unusual to throw an exception without creating an exception in advance). The real cost is to create an exception. Fortunately, good programming habits have taught us that we should not throw exceptions regardless of 3,721. Exceptions are designed for exceptional situations and should be kept in mind when used.



 </p><p>27. Collection </p><p> When the set is declared static, be sure to note that memory leaks are easily generated </p>


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.