1. 在循环中,能不使用复杂表达式,循环条件会被反复计算
class loop
public void loopMethod(ArrayList list){
for(int i=0;i<list.size();i++){
......
}
}
改为
class loop
public void loopMethod(ArrayList list){
int length = list.size();
for(int i=0;i<length;i++){
......
}
}
2.String,StringBuilder,StringBuffer
速度上StringBuilder>StringBuffer>String
String类是不可变类,任何对String的改变都 会引发新的String对象的生成;StringBuffer则是可变类,任何对它所指代的字符串的改变都不会产生新的对象
StringBuilder是线程非安全的,StringBuffer是线程安全的,在多线程的程序里面建议使用StringBuffer,其他情况使用StringBuilder
测试处理速度代码
package test;
public class StringTest {
//String 操作循环200万次
public static void operateString(){
String str = "a";
long startTime = System.currentTimeMillis();
for(int i=0;i<200000;i++){
str+="a";
}
long endTime = System.currentTimeMillis();
System.out.println((endTime-startTime)+" millis cost when user String");
}
//StringBuilder 操作循环2000万次
public static void operateStringBuilder(){
StringBuilder str = new StringBuilder("a");
long startTime = System.currentTimeMillis();
for(int i=0;i<20000000;i++){
str=str.append("a");
}
long endTime = System.currentTimeMillis();
System.out.println((endTime-startTime)+" millis cost when user StringBuilder");
}
//StringBuffer 操作循环2000万次
public static void operateStringBuffer(){
StringBuffer str = new StringBuffer("a");
long startTime = System.currentTimeMillis();
for(int i=0;i<20000000;i++){
str=str.append("a");
}
long endTime = System.currentTimeMillis();
System.out.println((endTime-startTime)+" millis cost when user StringBuffer");
}
public static void main(String[] args) {
operateString();
operateStringBuilder();
operateStringBuffer();
}
}
输出结果:
17539 millis cost when user String
183 millis cost when user StringBuilder
233 millis cost when user StringBuffer
3.gzip传输
当后端有大量数据需要传到前端时,使用gzip压缩后进行传输。
private void getMutipleMediaPlotData(HttpServletRequest request, HttpServletResponse response, JSONObject value){
List<Object> nodes = new List<Object>();
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gout = new GZIPOutputStream(out);
gout.write(JSON.toJSONString(nodes).getBytes());
gout.close();
byte[] result = out.toByteArray();
response.setHeader("Content-Encoding","gzip");
response.setHeader("Content-Length", result.length+"");
response.getOutputStream().write(result);
}
$.post(opts.url,opts.headers,opts.contentType).done(function(_data) {
if (_data) {
var result = null;
try{
result = JSON.parse(_data);
//result = eval("("+_data+")");
}catch (e){
result = [];
}
}
});