1. 程式人生 > >專案程式碼優化(五)

專案程式碼優化(五)

專案程式碼優化(五)

a.null和undefined的使用

  • 場景
if(parentValues == null || parentValues == undefined)
return [];
  • 解釋
  • 英文
Conditional statements using a condition which cannot be anything but false have the effect of making blocks of code non-functional. If the condition cannot evaluate to anything but true, the conditional statement is completely redundant, and makes the code less readable.

It is quite likely that the code does not match the programmer's intent.

Either the condition should be removed or it should be updated so that it does not always evaluate to true or false.
  • 中文
1.上面意思是說parentValues == undefined這個條件一直為false
2.區分null和undefined的區別,null表示的是不存在這個物件,而undefined表示,定義了一個未申明
的js變數。null typedof Object 為true,undefined typeof undefined為true,而且ECMAScript認為undefined是從null派生出來的,所以null == undefined為true,但是 null === undefined是false
3.解決方案:
if(parentValues == null)
return [];

b. indexOf(String)和indexOf(Char)的區別

  • 場景
String myStr = "Hello World";
int pos = myStr.indexOf("W");
int otherPos = myStr.lastIndexOf("r");
  • 解釋
  • 英文
An indexOf or lastIndexOf call with a single letter String can be made more performant by switching to a call with a char argument.
  • 中文
1.在字串查詢單個字元時,indexOf(String)要比indexOf(Char)消耗更多效能。
2.所以在單個字元進行匹配的情況下,建議使用indexOf(Char)的方式,例如:indexOf('w') 注意裡面是單引號
3.至於為什麼indexOf(String)效能消耗更多,建議檢視jdk原始碼,尚可知曉。

學習Java的同學注意了!!!
學習過程中遇到什麼問題或者想獲取學習資源的話,歡迎加入Java學習交流群,群號碼:543120397 我們一起學Java!