Optimization of Java code

This article comes from: CSDN Ali, a senior engineer to teach you how to optimize java code

Easy to remember, do code formatting, pornographic highlighted.

text:

First, make the code more performance

  1, if necessary Map the primary key and value should be iterative entrySet

  When the cycle requires only Map primary key, iteration keySet is correct. However, when you need a primary key and value, entrySet iterative approach is more efficient than the first iteration keySet then to get the value of better performance.

  Counterexample:  

Map<String, String> map = ...;
for (String key : map.keySet) {
    String value = map.get(key);
    ...
}

  Positive examples:  

Map<String, String> map = ...;
for (Map.Entry<String, String> entry : map.entrySet) {
    String key = entry.getKey;
    String value = entry.getValue;
    ...
}

  2, should be used Collection. IsEmpty empty detection

  Use Collection.size detected no empty logical problem, but using Collection. IsEmpty makes the code more readable, better performance can be obtained. Any Collection. Time complexity is achieved isEmpty O (1), but the time complexity of some Collection.size implementation may be O (n).

  Counterexample:

if (collection.size == 0) {
    ...
}

  Positive examples:

if (collection.isEmpty) {
    ...
}

  Detecting if required, may be employed CollectionUtils. IsEmpty (Collection) and CollectionUtils. IsNotEmpty (Collection).

  3, not to pass their own collection of objects

  In addition, some methods require parameters remain unchanged during the execution, so the collection passed to itself may result in unexpected behavior.

  Counterexample:

List < String > List new new = the ArrayList <> ; 
List.add ( "the Hello"); 
List.add ( "World"); 
IF ( list.containsAll (List) ) {// meaningless, always return to true 
    .. . 
} List.removeAll (List) ; // poor performance, directly clear

  4, the set of possible initialization specified size

  Java collection classes with very convenient, but look at the source code can be seen, the collection also has size limitations. Each expansion is likely to be time complexity O (n), it is possible to specify a set of predictable size, can reduce the number of expansion set.

  Counterexample:

int arr = new int{1, 2, 3};
List<Integer> list = new ArrayList<>;
for (int i : arr) {
    list.add(i);
}

  Positive examples:

int arr = new int{1, 2, 3};
List<Integer> list = new ArrayList<>(arr.length);
for (int i : arr) {
    list.add(i);
}

  5, string concatenation use StringBuilder

  Generally the strings together at compile Java will be optimized, but in a loop string concatenation, Java compile-time optimization can not be done, so it is necessary to use StringBuilder to be replaced.

  Counterexample:

String s = "";
for (int i = 0; i < 10; i++) {
    s += i;
}

  Positive examples:

A = String "A"; 
String B = "B"; 
String C = "C"; 
String S = A + B + C; // no problem, java compiler to optimize 
the StringBuilder the StringBuilder new new SB =; 
for (int 0 = I; I < 10 ; I ++) { 
    sb.append (I); // cycle, java compiler can not be optimized, so to manually use the StringBuilder }

  . 6, L random access to ist

  We all know the difference between an array and a linked list: more efficient random access array. When you call the method to get to L after ist, if you want to randomly access the data, does not know the internal array implementation is a linked list or array, how to do it? Can determine whether it implements * RandomAccess * interface.

  Positive examples:

// call the services of others to get List 
List < Integer > List = otherService.getList; 
IF (List instanceof the RandomAccess ) { 
    // internal array to achieve, can randomly access 
    System.out.println (list.get (list.size - 1 )); 
} the else { 
    // internal list may be achieved, the low efficiency of the random access 
}

  7, frequently called Collection.contains methods use the Set

  In the Java collection class library, L contains ist general method of time complexity of O (n), if a call to contains frequently find data in a code, l may be first converted into HashSet ist achieved, the O (n) of reduced time complexity of O (1).

  Counterexample:

ArrayList<Integer> list = otherService.getList;
for (int i = 0; i <= Integer.MAX_VALUE; i++) {
    // 时间复杂度O(n)
    list.contains(i);
}

  Positive examples:

ArrayList<Integer> list = otherService.getList;
Set<Integer> set = new HashSet(list);
for (int i = 0; i <= Integer.MAX_VALUE; i++) {
    // 时间复杂度O(1)
    set.contains(i);
}

 

Second, make the code more elegant  

  1, after a long integer constant is added capital L

  When using the long integer constant value, the latter need to add L, must be uppercase L, not lowercase l, l lowercase easily confused with the number 1 and misleading.

  Counterexample:

long value = 1l;long max = Math.max(1L, 5);

  Positive examples:

long value = 1L;
long max = Math.max(1L, 5L);

  2. Do not use mana

  When you write a piece of code, use mana may seem clear, but they do not appear when debugging so clear. This is why the magic value is defined as the reason can be read constants. However, -1, 0 and 1 are not considered mana. (Mana is not a literal string variable assignment and there is no point of reference)

  Counterexample:

for (int i = 0; i < 100; i++){
    ...
}
if (a == 100) {
    ...
}

  Positive examples:

private static final int MAX_COUNT = 100;
for (int i = 0; i < MAX_COUNT; i++){
    ...
}
if (count == MAX_COUNT) {
    ...
}

  3. Do not use a set of implementation to assign a static member variables

  For static member variables collection types, do not use the set to achieve the assignment, you should use static code block assignment.

  Counterexample:

private static Map<String, Integer> map = new HashMap<String, Integer> {
  {
    put("a", 1);
    put("b", 2);
  }
};

private static List<String> list = new ArrayList<String> {
  {
    add("a");
    add("b");
  }
};

  Positive examples:

private static Map<String, Integer> map = new HashMap<>;
static {
  map.put("a", 1);
  map.put("b", 2);
};

private static List<String> list = new ArrayList<>;
static {
  list.add("a");
  list.add("b");
};

  4, recommended the use of try-with-resources statement

  Java 7 introduced a try-with-resources statement, which can guarantee the resources to close, better than the original try-catch-finally statement, and make the program more concise code more secure.

  Counterexample:

private void handle(String fileName) {
  BufferedReader reader = ;
  try {
    String line;
    reader = new BufferedReader(new FileReader(fileName));
    while ((line = reader.readLine) != ) {
      ...
    }
  } catch (Exception e) {
    ...
  } finally {
    if (reader != ) {
      try {
        reader.close;
      } catch (IOException e) {
        ...
      }
    }
  }
}

  Positive examples:

private void handle(String fileName) {
  try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
    String line;
    while ((line = reader.readLine) != ) {
      ...
    }
  } catch (Exception e) {
    ...
  }
}

  5, delete unused private methods and fields of

  Delete unused private methods and fields, and make the code more concise and easier to maintain. If necessary re-use, from back in the history of submission.

  Counterexample:

public class DoubleDemo1 {
  private int unusedField = 100;
  private void unusedMethod {
    ...
  }
  public int sum(int a, int b) {
    return a + b;
  }
}

  Positive examples:

public class DoubleDemo1 {
  public int sum(int a, int b) {
    return a + b;
  }
}

  6, delete unused local variables

  Delete unused local variables to make the code more concise and easier to maintain.

  Counterexample:

public int sum(int a, int b) {
    int c = 100;
    return a + b;
}

  Positive examples:

public int sum(int a, int b) {
  return a + b;
}

  7, delete unused method parameters

  The method parameter is not used misleading, delete unused method parameters, to make the code more concise and easier to maintain. However, since the method is a method to rewrite the parent class or interface defined based on, even if there is an unused parameter method, but also it can not be deleted.

  Counterexample:

public int sum(int a, int b, int c) {
  return a + b;
}

  Positive examples:

public int sum(int a, int b) {
  return a + b;
}

  8, delete unnecessary expression in parentheses

  The corresponding expression extra brackets, it was thought to contribute code readers, some people feel totally unnecessary. For a people who are familiar with Java syntax, expressions extra parentheses would give the code is more complicated.

  Counterexample:

return (x);
return (x + 2);
int x = (y * 3) + 1;
int m = (n * 4 + 2);

  Positive examples:

return x;
return x + 2;
int x = y * 3 + 1;
int m = n * 4 + 2;

  9, tools should be shielded constructor

  Is a collection of tools and functions pile static field, it should not be instantiated. However, Java adds an implicit public constructor for each class is not explicitly defined constructor. Therefore, in order to avoid java "white" incorrect use, you should explicitly defined to shield the private constructors implicit public constructor.

  Counterexample:

public class MathUtils {
  public static final double PI = 3.1415926D;
  public static int sum(int a, int b) {
    return a + b;
  }
}

  Positive examples:

public class MathUtils {
  public static final double PI = 3.1415926D;
  private MathUtils {}
  public static int sum(int a, int b) {
    return a + b;
  }
}

  10, remove the extra exception caught and thrown

  After capturing an exception with catch phrase, nothing is processed, re-let an exception is thrown, this result is not like catching exceptions, you can delete or add another piece of code that process.

  Counterexample:

private static String readFile(String fileName) throws IOException {
  try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
    String line;
    StringBuilder builder = new StringBuilder;
    while ((line = reader.readLine) != ) {
      builder.append(line);
    }
    return builder.toString;
  } catch (Exception e) {
    throw e;
  }
}

  Positive examples:

private static String readFile(String fileName) throws IOException {
  try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
    String line;
    StringBuilder builder = new StringBuilder;
    while ((line = reader.readLine) != ) {
      builder.append(line);
    }
    return builder.toString;
  }
}

  11, public static constant access should be through the class

  Although instances of access by public static class constants are allowed, but easy to mistake it for an instance of each class has a public static constant. Therefore, public static class constants should be directly accessible through.

  Counterexample:

public class User {
  public static final String CONST_NAME = "name";
  ...
}

User user = new User;
String nameKey = user.CONST_NAME;

  Positive examples:

public class User {
  public static final String CONST_NAME = "name";
  ...
}

String nameKey = User.CONST_NAME;

  12, do not judge by empty PointerException

  Null pointer exception should avoid the code (such as detector is not empty), instead of processing the captured abnormal manner.

  Counterexample:

public String getUserName(User user) {
  try {
    return user.getName;
  } catch (PointerException e) {
    return ;
  }
}

  Positive examples:

public String getUserName(User user) {
  if (Objects.isNull(user)) {
    return ;
  }
  return user.getName;
}

  13, using String.valueOf (value) instead of "" + value

  When the type or other objects should be converted to a string, using String.valueOf (value) "" + is higher than the efficiency value.

  Counterexample:

int i = 1;
String s = "" + i;

  Positive examples:

int i = 1;
String s = String.valueOf(i);

  14, obsolete code to add comment @Deprecated

  When a piece of code out of date, but in order to be compatible and can not be directly deleted, you do not want someone to use it later, you can add annotations @Deprecated marked. @Deprecated add comments in the document to explain and offer alternatives

  Positive examples:

/ ** 
* Save 
* 
* @deprecated low efficiency of this method, use {@link newSave} replacing it 
* / @Deprecated 
public void Save { 
  // do something 
}

Third, make the code away from Bug

  1, prohibits the use constructor BigDecimal (double)

  BigDecimal (double) the presence of risk of loss of precision, the exact calculation of the comparison values ​​or the scene may cause the business logic exception.

  Counterexample:

BigDecimal value = new BigDecimal(0.1D); // 0.100000000000000005551115...

  Positive examples:

BigDecimal value = BigDecimal.valueOf(0.1D);; // 0.1

  2, returns an empty array and an empty collection instead

  Return, the caller requires mandatory testing, otherwise it will throw a null pointer exception. Returns an empty array or an empty set, effectively avoided because the caller does not detect null pointer exception is thrown, you can also delete the caller detects statement makes the code more concise.

  Counterexample:

public static Result getResults {
  return ;
}

public static List<Result> getResultList {
  return ;
}

public static Map<String, Result> getResultMap {
  return ;
}

public static void main(String[] args) {
  Result results = getResults;
  if (results != ) {
    for (Result result : results) {
      ...
    }
  }

  List<Result> resultList = getResultList;
  if (resultList != ) {
    for (Result result : resultList) {
      ...
    }
  }

  Map<String, Result> resultMap = getResultMap;
  if (resultMap != ) {
    for (Map.Entry<String, Result> resultEntry : resultMap) {
      ...
    }
  }
}

  Positive examples:

public static Result getResults {
  return new Result[0];
}

public static List<Result> getResultList {
  return Collections.emptyList;
}

public static Map<String, Result> getResultMap {
  return Collections.emptyMap;
}

public static void main(String[] args) {
  Result results = getResults;
  for (Result result : results) {
    ...
  }

  List<Result> resultList = getResultList;
  for (Result result : resultList) {
    ...
  }

  Map<String, Result> resultMap = getResultMap;
  for (Map.Entry<String, Result> resultEntry : resultMap) {
    ...
  }
}

  3, the priority is determined using a constant value or equals method to call

  equals method of Object readily shorting pointer exception, should be used with a constant value or determined object to call the equals method. Of course, the best practice is to use java.util.Objects.equals.

  Counterexample:

void isFinished public (OrderStatus Status) { 
  return status.equals (OrderStatus.FINISHED); // pointer exception may shorting 
}

  Positive examples:

public void isFinished(OrderStatus status) {
  return OrderStatus.FINISHED.equals(status);
}

public void isFinished(OrderStatus status) {
  return Objects.equals(status, OrderStatus.FINISHED);
}

  4, enumeration of private property field must be immutable

  Enumeration is generally used as a constant, or if the common attribute field setting field enumeration methods exist, then the enumeration constant properties can easily be modified. Ideally, the attribute field enumeration is private and the private constructor assignment, there is no corresponding method Setter, preferably together with the final modifier.

  Counterexample:

public enum UserStatus {
  DISABLED(0, "禁用"),
  ENABLED(1, "启用");

  public int value;
  private String description;

  private UserStatus(int value, String description) {
    this.value = value;
    this.description = description;
  }

  public String getDescription {
    return description;
  }

  public void setDescription(String description) {
    this.description = description;
  }
}

  Positive examples:

public enum UserStatus {
  DISABLED(0, "禁用"),
  ENABLED(1, "启用");

  private final int value;
  private final String description;

  private UserStatus(int value, String description) {
    this.value = value;
    this.description = description;
  }

  public int getValue {
    return value;
  }

  public String getDescription {
    return description;
  }
}

  5, careful String.split (String regex)

  String String split method, passing in the delimited string is a regular expression! Some of the keywords (such as [] () \ |., Etc.) need to escape

  Counterexample:

"a.ab.abc".split("."); // 结果为
"a|ab|abc".split("|"); // 结果为["a", "|", "a", "b", "|", "a", "b", "c"]

  Positive examples:

"a.ab.abc".split("\\."); // 结果为["a", "ab", "abc"]
"a|ab|abc".split("\\|"); // 结果为["a", "ab", "abc"]

 

Guess you like

Origin www.cnblogs.com/HF-Made/p/11634869.html