淺談Java開發規範與開發細節(下)

上篇我們簡單分析了一下規範中的命名規範、變量申明的時機、if與大括號的規範、包裝類與基礎類型常見問題和規範以及項目開發中的空指針等問題,本篇我們繼續聊聊幾個常見的但是企業開發中比較容易忽略的細節。

不要使用枚舉類型作爲返回值

還記得阿里巴巴Java開發手冊上有很多地方提到了關於枚舉的規範:

【參考】枚舉類名帶上 Enum 後綴,枚舉成員名稱需要全大寫,單詞間用下劃線隔開。說明:枚舉其實就是特殊的類,域成員均爲常量,且構造方法被默認強制是私有。

【推薦】如果變量值僅在一個固定範圍內變化用 enum 類型來定義。

【強制】二方庫裏可以定義枚舉類型,參數可以使用枚舉類型,但是接口返回值不允許使用枚舉類型或者包含枚舉類型的 POJO 對象。

一個是推薦的參考命名規範,一個是推薦的使用方法,但是我們注意到有一個強制的規範,一般情況下強制的規範都是爲了避免企業開發一些細節的風險而標記出來的,可以看到阿里手冊中有提到不允許在接口交互過程中使用枚舉類型的參數進行傳遞,那麼這是爲什麼呢?

我們知道,枚舉的使用場景一般爲在需要一組同類型的固定常量的時候,我們可以使用枚舉來作爲標記替代,因此枚舉類不需要多例存在,保證了單例以後則是可以減少了內存開銷。

**並且我們也知道,在編寫枚舉的時候,如果出現如果被 abstract 或 final 修飾,或者是枚舉常量重複,都會立刻被編譯器報錯。並且在整個枚舉類中,除了當前的枚舉常量以外,並不存在其他的任何實例。**因爲有了這些特性,使得我們在開發過程中,使用常量的時候比較容易。

但是我們深入瞭解後,**可以知道枚舉的clone方法被final修飾,因此enum常量並不會被克隆,並且枚舉類禁止通過反射創建實例,保證了絕對的單例,在反序列化的過程中,枚舉類不允許出現實例不相同的情況。**而枚舉類在使用過程中最重要的兩個方法分別是:

1.用來根據枚舉名稱獲取對應枚舉常量的 publicstaticT valueOf(String)方法

2.用來獲取當前所有的枚舉常量的 publicstaticT[]values()方法

3.用來克隆的函數- clone

我們分別根據這幾個方法來研究下爲什麼有枚舉的這幾個規範,首先我們來看看clone方法的註釋:


1.  `/**`

2.  `* Throws CloneNotSupportedException. This guarantees that enums`

3.  `* are never cloned, which is necessary to preserve their "singleton"`

4.  `* status.`

5.  `*`

6.  `* @return (never returns)`

7.  `*/`

</pre>

從註釋上我們就能看出來,枚舉類型不支持clone方法,如果我們調用clone方法,會拋 CloneNotSupportedException異常,而與之相關的還有反射創建實例的 newInstance方法,我們都知道,如果不調用clone方法,一般可以使用反射,並且setAccessible 爲 true 後調用 newInstance方法,即可構建一個新的實例,而我們可以看到此方法的源碼:

1.  `public T newInstance(Object... initargs)`

2.  `throwsInstantiationException, IllegalAccessException,`

3.  `IllegalArgumentException, InvocationTargetException`

4.  `{`

5.  `.........`

6.  `//如果當前的類型爲枚舉類型,那麼調用當前方法直接拋異常`

7.  `if((clazz.getModifiers() & Modifier.ENUM) != 0)`

8.  `thrownewIllegalArgumentException("Cannot reflectively create enum objects");`

10.  `.........`

11.  `return inst;`

12.  `}`

</pre>

從這我們可以看出,枚舉爲了**保證不能被克隆,維持單例的狀態,禁止了clone和反射創建實例。**那麼我們接着來看序列化,由於所有的枚舉都是Eunm類的子類及其實例,而Eunm類默認實現了 SerializableComparable接口,所以默認允許進行排序和序列化,而排序的方法 compareTo的實現大概如下:


1.  `/**`

2.  `* Compares this enum with the specified object for order. Returns a`

3.  `* negative integer, zero, or a positive integer as this object is less`

4.  `* than, equal to, or greater than the specified object.`

5.  `*`

6.  `* Enum constants are only comparable to other enum constants of the`

7.  `* same enum type. The natural order implemented by this`

8.  `* method is the order in which the constants are declared.`

9.  `*/`

10.  `public  final  int compareTo(E o)  {`

11.  `Enum<?> other =  (Enum<?>)o;`

12.  `Enum<E> self =  this;`

13.  `if  (self.getClass()  != other.getClass()  &&  // optimization`

14.  `self.getDeclaringClass()  != other.getDeclaringClass())`

15.  `throw  new  ClassCastException();`

16.  `return self.ordinal - other.ordinal;`

17.  `}`

</pre>

而ordinal則是代表每個枚舉常量對應的申明順序,說明枚舉的排序方式默認按照申明的順序進行排序,那麼序列化和反序列化的過程是什麼樣的呢?我們來編寫一個序列化的代碼,debug跟代碼以後,可以看到最終是調用了 java.lang.Enum#valueOf方法來實現的反序列化的。而序列化後的內容大概如下:


1.  `arn_enum.CoinEnum?xr?java.lang.Enum?xpt?PENNYq?t?NICKELq?t?DIMEq~?t?QUARTER`

</pre>

大概可以看到,序列化的內容主要包含枚舉類型和枚舉的每個名稱,接着我們看看 java.lang.Enum#valueOf方法的源碼:


1.  `/**`

2.  `* Returns the enum constant of the specified enum type with the`

3.  `* specified name. The name must match exactly an identifier used`

4.  `* to declare an enum constant in this type. (Extraneous whitespace`

5.  `* characters are not permitted.)`

6.  `*`

7.  `* <p>Note that for a particular enum type {@code T}, the`

8.  `* implicitly declared {@code public static T valueOf(String)}`

9.  `* method on that enum may be used instead of this method to map`

10.  `* from a name to the corresponding enum constant. All the`

11.  `* constants of an enum type can be obtained by calling the`

12.  `* implicit {@code public static T[] values()} method of that`

13.  `* type.`

14.  `*`

15.  `* @param <T> The enum type whose constant is to be returned`

16.  `* @param enumType the {@code Class} object of the enum type from which`

17.  `* to return a constant`

18.  `* @param name the name of the constant to return`

19.  `* @return the enum constant of the specified enum type with the`

20.  `* specified name`

21.  `* @throws IllegalArgumentException if the specified enum type has`

22.  `* no constant with the specified name, or the specified`

23.  `* class object does not represent an enum type`

24.  `* @throws NullPointerException if {@code enumType} or {@code name}`

25.  `* is null`

26.  `* @since 1.5`

27.  `*/`

28.  `public  static  <T extends  Enum<T>> T valueOf(Class<T> enumType,`

29.  `String name)  {`

30.  `T result = enumType.enumConstantDirectory().get(name);`

31.  `if  (result !=  null)`

32.  `return result;`

33.  `if  (name ==  null)`

34.  `throw  new  NullPointerException("Name is null");`

35.  `throw  new  IllegalArgumentException(`

36.  `"No enum constant "  + enumType.getCanonicalName()  +  "."  + name);`

37.  `}`

</pre>

從源碼和註釋中我們都可以看出來,如果此時A服務使用的枚舉類爲舊版本,只有五個常量,而B服務的枚舉中包含了新的常量,這個時候在反序列化的時候,由於name == null,則會直接拋出異常,從這我們也終於看出來,爲什麼規範中會強制不允許使用枚舉類型作爲參數進行序列化傳遞了。

慎用可變參數

在翻閱各大規範手冊的時候,我看到阿里手冊中有這麼一條:

【強制】相同參數類型,相同業務含義,纔可以使用 Java 的可變參數,避免使用 Object 。說明:可變參數必須放置在參數列表的最後。(提倡同學們儘量不用可變參數編程)

正例: public ListlistUsers(String type, Long… ids) {…}

吸引了我,因爲在以前開發過程中,我就遇到了一個可變參數埋下的坑,接下來我們就來看看可變參數相關的一個坑。

相信很多人都編寫過企業裏使用的工具類,而我當初在編寫一個Boolean類型的工具類的時候,編寫了大概如下的兩個方法:


1.  `private  static  boolean and(boolean... booleans)  {`

2.  `for  (boolean b : booleans)  {`

3.  `if  (!b)  {`

4.  `return  false;`

5.  `}`

6.  `}`

7.  `return  true;`

8.  `}`

10.  `private  static  boolean and(Boolean... booleans)  {`

11.  `for  (Boolean b : booleans)  {`

12.  `if  (!b)  {`

13.  `return  false;`

14.  `}`

15.  `}`

16.  `return  true;`

17.  `}`

</pre>

這兩個方法看起來就是一樣的,都是爲了傳遞多個布爾類型的參數進來,判斷多個條件連接在一起,是否能成爲true的結果,但是當我編寫測試的代碼的時候,問題出現了:

1.  `public  static  void main(String[] args)  {`

2.  `boolean result = and(true,  true,  true);`

3.  `System.out.println(result);`

4.  `}`

</pre>

這樣的方法會返回什麼呢?其實當代碼剛剛編寫完畢的時候,就會發現編譯器已經報錯了,會提示:

1.  `Ambiguous method call. Both and (boolean...) in BooleanDemo and  and (Boolea`

2.  `n...) in BooleanDemo match.`

</pre>

模糊的函數匹配,因爲編譯器認爲有兩個方法都完全滿足當前的函數,那麼爲什麼會這樣的呢?我們知道在Java1.5以後加入了自動拆箱裝箱的過程,爲了兼容1.5以前的jdk版本,將此過程設置爲了三個階段:

而我們使用的測試方法中,在第一階段,判斷jdk版本,是不是不允許自動裝箱拆箱,明顯jdk版本大於1.5,允許自動拆箱裝箱,因此進入第二階段,此時判斷是否存在更符合的參數方法,比如我們傳遞了三個布爾類型的參數,但是如果此時有三個布爾參數的方法,則會優先匹配此方法,而不是匹配可變參數的方法,很明顯也沒有,此時就會進入第三階段,完成裝箱拆箱以後,再去查找匹配的變長參數的方法,這個時候由於完成了拆箱裝箱,兩個類型會視爲一個類型,發現方法上有兩個匹配的方法,這時候就會報錯了。

那麼我們有木有辦法處理這個問題呢?畢竟我們熟悉的 org.apache.commons.lang3.BooleanUtils工具類中也有類似的方法,我們都明白,變長參數其實就是會將當前的多個傳遞的參數裝入數組後,再去處理,那麼可以在傳遞的過程中,將所有的參數通過數組包裹,這個時候就不會發生拆箱裝箱過程了!例如:


1.  `@Test`

2.  `public  void testAnd_primitive_validInput_2items()  {`

3.  `assertTrue(`

4.  `!  BooleanUtils.and(new  boolean[]  {  false,  false  })`

5.  `}`

</pre>

而參考其他框架源碼大神的寫法中,也有針對這個的編寫的範例:

通過此種方法可以保證如果傳入的是基本類型,直接匹配當前方法,如果是包裝類型,則在第二階段以後匹配到當前函數,最終都是調用了BooleanUtils中基本類型的and方法。

List的去重與xxList方法

List作爲我們企業開發中最常見的一個集合類,在開發過程中更是經常遇到去重,轉換等操作,但是集合類操作的不好很多時候會導致我們的程序性能緩慢或者出現異常的風險,例如阿里手冊中提到過:

【 強 制 】ArrayList的subList結果不可強轉成 ArrayList,否則會拋出ClassCastException異常,即java.util.RandomAccessSubList cannot be cast to java.util.ArrayList。

【強制】在SubList場景中,高度注意對原集合元素的增加或刪除,均會導致子列表的 遍歷、增加、刪除產生 ConcurrentModificationException 異常。

【強制】使用工具類 Arrays.asList () 把數組轉換成集合時,不能使用其修改集合相關的 方法,它的add/remove/clear 方法會拋出 UnsupportedOperationException 異常。

而手冊中的這些xxList方法則是我們開發過程中比較常用的,那麼爲什麼阿里手冊會有這些規範呢?我們來看看第一個方法 subList,首先我們先看看SubList類和ArrayList類的區別,從類圖上我們可以看出來兩個類之間並沒有繼承關係:

所以手冊上不允許使用 subList強轉爲ArrayList,那麼爲什麼原集合不能進行增刪改查操作呢?我們來看看其源碼:


1.  `/**`

2.  `* Returns a view of the portion of this list between the specified`

3.  `* {@code fromIndex}, inclusive, and {@code toIndex}, exclusive. (If`

4.  `* {@code fromIndex} and {@code toIndex} are equal, the returned list is`

5.  `* empty.) The returned list is backed by this list, so non-structural`

6.  `* changes in the returned list are reflected in this list, and vice-versa.`

7.  `* The returned list supports all of the optional list operations.`

8.  `*`

9.  `* <p>This method eliminates the need for explicit range operations (of`

10.  `* the sort that commonly exist for arrays). Any operation that expects`

11.  `* a list can be used as a range operation by passing a subList view`

12.  `* instead of a whole list. For example, the following idiom`

13.  `* removes a range of elements from a list:`

14.  `* <pre>`

15.  `* list.subList(from, to).clear();`

16.  `* </pre>`

17.  `* Similar idioms may be constructed for {@link #indexOf(Object)} and`

18.  `* {@link #lastIndexOf(Object)}, and all of the algorithms in the`

19.  `* {@link Collections} class can be applied to a subList.`

20.  `*`

21.  `* <p>The semantics of the list returned by this method become undefined if`

22.  `* the backing list (i.e., this list) is <i>structurally modified</i> in`

23.  `* any way other than via the returned list. (Structural modifications are`

24.  `* those that change the size of this list, or otherwise perturb it in such`

25.  `* a fashion that iterations in progress may yield incorrect results.)`

26.  `*`

27.  `* @throws IndexOutOfBoundsException {@inheritDoc}`

28.  `* @throws IllegalArgumentException {@inheritDoc}`

29.  `*/`

30.  `publicList<E> subList(int fromIndex, int toIndex) {`

31.  `subListRangeCheck(fromIndex, toIndex, size);`

32.  `returnnewSubList(this, 0, fromIndex, toIndex);`

33.  `}`

</pre>

我們可以看到代碼的邏輯只有兩步,第一步檢查當前的索引和長度是否變化,第二步構建新的SubList出來並且返回。從註釋我們也可以瞭解到,SubList中包含的範圍,如果對其進行增刪改查操作,都會導致原來的集合發生變化,並且是從當前的index + offSet進行變化。

那麼爲什麼我們這個時候對原來的ArrayList進行增刪改查操作的時候會導致SubList集合操作異常呢?我們來看看ArrayList的add方法:


1.  `/**`

2.  `* Appends the specified element to the end of this list.`

3.  `*`

4.  `* @param e element to be appended to this list`

5.  `* @return <tt>true</tt> (as specified by {@link Collection#add})`

6.  `*/`

7.  `publicboolean add(E e) {`

8.  `ensureCapacityInternal(size + 1); // Increments modCount!!`

9.  `elementData[size++] = e;`

10.  `returntrue;`

11.  `}`

</pre>

我們可以看到一點,每次元素新增的時候都會有一個 ensureCapacityInternal(size+1);操作,這個操作會導致modCount長度變化,而modCount則是在SubList的構造中用來記錄長度使用的:

1.  `SubList(AbstractList<E> parent,`

2.  `int offset,  int fromIndex,  int toIndex)  {`

3.  `this.parent = parent;`

4.  `this.parentOffset = fromIndex;`

5.  `this.offset = offset + fromIndex;`

6.  `this.size = toIndex - fromIndex;`

7.  `this.modCount =  ArrayList.this.modCount;  // 注意:此處複製了 ArrayList的 modCount`

8.  `}`

</pre>

而SubList的get操作的源碼如下:

1.  `public E get(int index) {`

2.  `rangeCheck(index);`

3.  `checkForComodification();`

4.  `returnArrayList.this.elementData(offset + index);`

5.  `}`

</pre>

可以看到每次都會去校驗一下下標和modCount,我們來看看 checkForComodification方法:

1.  `private  void checkForComodification()  {`

2.  `if  (ArrayList.this.modCount !=  this.modCount)`

3.  `throw  new  ConcurrentModificationException();`

4.  `}`

</pre>

可見每次都會檢查,如果發現原來集合的長度變化了,就會拋出異常,那麼使用SubList的時候爲什麼要注意原集合是否被更改的原因就在這裏了。

那麼爲什麼asList方法的集合不允許使用新增、修改、刪除等操作呢?

我們來看下和ArrayList的方法比較:

很明顯我們能看出來,asList構建出來的List沒有重寫 addremove 函數,說明該類的集合操作的方法來自父類 AbstactList,我們來看看父類的add方法:

1.  `public  void add(int index, E element)  {`

2.  `throw  new  UnsupportedOperationException();`

3.  `}`

</pre>

從這我們可以看出來,如果我們進行add或者remove操作,會直接拋異常。

集合去重操作

我們再來看一個企業開發中最常見的一個操作,將List集合進行一次去重操作,我本來以爲每個人都會選擇使用 Set來進行去重,可是當我翻看團隊代碼的時候發現,居然很多人偷懶選了List自帶的 contains方法判斷是否存在,然後進行去重操作!我們來看看一般我們使用Set去重的時候編寫的代碼:

1.  `public  static  <T>  Set<T> removeDuplicateBySet(List<T> data)  {`

2.  `if  (CollectionUtils.isEmpty(data))  {`

3.  `return  new  HashSet<>();`

4.  `}`

5.  `return  new  HashSet<>(data);`

6.  `}`

</pre>

而HashSet的構造方法如下:


1.  `publicHashSet(Collection<? extends E> c) {`

2.  `map = newHashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));`

3.  `addAll(c);`

4.  `}`

</pre>

主要是創建了一個HashMap以後進行addAll操作,我們來看看addAll方法:

1.  `public  boolean addAll(Collection<?  extends E> c)  {`

2.  `boolean modified =  false;`

3.  `for  (E e : c)`

4.  `if  (add(e))`

5.  `modified =  true;`

6.  `return modified;`

7.  `}`

</pre>

從這我們也可以看出來,內部循環調用了add方法進行元素的添加:


1.  `public  boolean add(E e)  {`

2.  `return map.put(e, PRESENT)==null;`

3.  `}`

</pre>

而add方法內部依賴了hashMap的put方法,我們都知道hashMap的put方法中的key是唯一的,即天然可以避免重複,我們來看看key的hash是如何計算的:

1.  `static  final  int hash(Object key)  {`

2.  `int h;`

3.  `return  (key ==  null)  ?  0  :  (h = key.hashCode())  ^  (h >>>  16);`

4.  `}`

</pre>

可以看到如果 key 爲 null ,哈希值爲 0,否則將 key 通過自身 hashCode 函數計算的的哈希值和其右移 16 位進行異或運算得到最終的哈希值,而在最終的 putVal方法中,判斷是否存在的邏輯如下:


1.  `p.hash == hash && ((k = p.key) == key || (key != null&& key.equals(k)))`

</pre>

而看到這我們基本已經明瞭了,set的hash計算還是依靠元素自身的hashCode計算,只要我們需要去重的元素實例遵循了重寫hashCode也重寫equals的規則,保持一致,直接使用set進行去重還是很簡單的。反過來我們再來看看List的 contains方法的實現:

1.  `/**`

2.  `* Returns <tt>true</tt> if this list contains the specified element.`

3.  `* More formally, returns <tt>true</tt> if and only if this list contains`

4.  `* at least one element <tt>e</tt> such that`

5.  `* <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>.`

6.  `*`

7.  `* @param o element whose presence in this list is to be tested`

8.  `* @return <tt>true</tt> if this list contains the specified element`

9.  `*/`

10.  `public  boolean contains(Object o)  {`

11.  `return indexOf(o)  >=  0;`

12.  `}`

</pre>

可以看到其實是依賴於indexOf方法來判斷的:


1.  `/**`

2.  `* Returns the index of the first occurrence of the specified element`

3.  `* in this list, or -1 if this list does not contain the element.`

4.  `* More formally, returns the lowest index <tt>i</tt> such that`

5.  `* <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,`

6.  `* or -1 if there is no such index.`

7.  `*/`

8.  `public  int indexOf(Object o)  {`

9.  `if  (o ==  null)  {`

10.  `for  (int i =  0; i < size; i++)`

11.  `if  (elementData[i]==null)`

12.  `return i;`

13.  `}  else  {`

14.  `for  (int i =  0; i < size; i++)`

15.  `if  (o.equals(elementData[i]))`

16.  `return i;`

17.  `}`

18.  `return  -1;`

19.  `}`

</pre>

可以看到indexOf的邏輯爲,如果爲null,則遍歷全部元素判斷是否有null,如果不爲null也會遍歷所有元素的equals方法來判斷是否相等,所以時間複雜度接近 O(n^2),而Set的containsKey方法主要依賴於getNode方法:

1.  `/**`

2.  `* Implements Map.get and related methods.`

3.  `*`

4.  `* @param hash hash for key`

5.  `* @param key the key`

6.  `* @return the node, or null if none`

7.  `*/`

8.  `finalNode<K,V> getNode(int hash, Object key) {`

9.  `Node<K,V>[] tab; Node<K,V> first, e; int n; K k;`

10.  `if((tab = table) != null&& (n = tab.length) > 0&&`

11.  `(first = tab[(n - 1) & hash]) != null) {`

12.  `if(first.hash == hash && // always check first node`

13.  `((k = first.key) == key || (key != null&& key.equals(k))))`

14.  `return first;`

15.  `if((e = first.next) != null) {`

16.  `if(first instanceofTreeNode)`

17.  `return((TreeNode<K,V>)first).getTreeNode(hash, key);`

18.  `do{`

19.  `if(e.hash == hash &&`

20.  `((k = e.key) == key || (key != null&& key.equals(k))))`

21.  `return e;`

22.  `} while((e = e.next) != null);`

23.  `}`

24.  `}`

25.  `returnnull;`

26.  `}`

</pre>

可以看到優先通過計算的hash值找到table的第一個元素比較,如果相等直接返回第一個元素,如果是樹節點則從樹種查找,不是則從鏈中查找,可以看出來,如果hash衝突不是很嚴重的話,查找的速度接近 O(n),很明顯看出來,如果數量較多的話,List的 contains速度甚至可能差距幾千上萬倍!

字符串與拼接

在Java核心庫中,有三個字符串操作的類,分別爲 StringStringBufferStringBuilder,那麼勢必會涉及到一個問題,企業開發中經常使用到字符串操作,例如字符串拼接,但是使用的不對會導致出現大量的性能陷阱,那麼在什麼場合下使用String拼接什麼時候使用其他的兩個比較好呢?我們先來看一個案例:

1.  `public  String measureStringBufferApend()  {`

2.  `StringBuffer buffer =  new  StringBuffer();`

3.  `for  (int i =  0; i <  10000; i++)  {`

4.  `buffer.append("hello");`

5.  `}`

6.  `return buffer.toString();`

7.  `}`

9.  `//第二種寫法`

10.  `public  String measureStringBuilderApend()  {`

11.  `StringBuilder builder =  new  StringBuilder();`

12.  `for  (int i =  0; i <  10000; i++)  {`

13.  `builder.append("hello");`

14.  `}`

15.  `return builder.toString();`

16.  `}`

18.  `//直接String拼接`

19.  `public  String measureStringApend()  {`

20.  `String targetString =  "";`

21.  `for  (int i =  0; i <  10000; i++)  {`

22.  `targetString +=  "hello";`

23.  `}`

24.  `return targetString;`

25.  `}`

</pre>

使用JMH測試的性能測試結果可以看出來,使用StringBuffer拼接比String += 的方式效率快了200倍,StringBuilder的效率比Stirng += 的效率快了700倍,這是爲什麼呢?

原來String的 += 操作的時候每一次都需要創建一個新的String對象,然後將兩次的內容copy進來,再去銷燬原來的String對象,再去創建。。。。而StringBuffer和StringBuilder之所以快,是因爲內部預先分配了一部分內存,只有在內存不足的時候,纔會去擴展內存,而StringBuffer和StringBuilder的實現幾乎一樣,唯一的區別就是方法都是 synchronized包裝,保證了在併發下的字符串操作的安全性,因此導致性能會有一定幅度的下降。

那麼是不是String拼接一定就是最快的呢?

也不一定,例如下面的例子:


1.  `public  void measureSimpleStringApend()  {`

2.  `for  (int i =  0; i <  10000; i++)  {`

3.  `String targetString =  "Hello, "  +  "world!";`

4.  `}`

5.  `}`

6.  `//StringBuilder拼接`

7.  `public  void measureSimpleStringBuilderApend()  {`

8.  `for  (int i =  0; i <  10000; i++)  {`

9.  `StringBuilder builder =  new  StringBuilder();`

10.  `builder.append("hello, ");`

11.  `builder.append("world!");`

12.  `}`

13.  `}`

</pre>

相信有經驗的就會發現,直接兩個字符串片段直接 + 的拼接方式,效率竟然比StringBuilder還要快!這個巨大的差異,主要來自於 Java 編譯器和 JVM 對字符串處理的優化。" Hello, " + "world! " 這樣的表達式,並沒有真正執行字符串連接。

編譯器會把它處理成一個連接好的常量字符串"Hello, world!"。這樣,也就不存在反覆的對象創建和銷燬了,常量字符串的連接顯示了超高的效率。

但是我們需要注意一點,如果說拼接的兩個字符串不是片段常量,而是一個變量,那麼效率就會急劇下降,jvm是無法對字符串變量操作進行優化的,例如:


1.  `public  void measureVariableStringApend()  {`

2.  `for  (int i =  0; i <  10000; i++)  {`

3.  `String targetString =  "Hello, "  + getAppendix();`

4.  `}`

5.  `}`

7.  `private  String getAppendix()  {`

8.  `return  "World!";`

9.  `}`

</pre>

因此我們可以從中總結出來,使用字符串拼接的幾個實踐建議:

1.Java 的編譯器會優化常量字符串的連接,我們可以放心地把長的字符串換成多行,需要注意的是使用 + 拼接常量,而不是 += ,這兩個是不同的概念。

2.帶有變量的字符串連接,StringBuilder 效率更高。如果效率敏感的代碼,建議使用StringBuilder,並且在日常開發中一般都不建議使用StringBuffer,除非當前的確有嚴格的併發安全的要求。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章