代码优化与sql优化

  万丈高楼平地起,还是得打一个好地基呀

减少对变量对重复计算
//一般这么写
for (int i = 0; i < list.size(); i++)
{...}
//建议修改为:
for (int i = 0, length = list.size(); i < length; i++)
{...}
避免使用split(由于支持正则表达式效率比较低)
String str = "a,b,c,d,,f,g"; 
//一般这么写
String[] array = str.split(",");
//可以考虑使用apache的StringUtils.split(string,char)
String[] array = StringUtils.split(str1, ",");
//也可以考虑guava工具
List<String> list1=Splitter.on(",").splitToList(str1);
代码更简洁
if (isdone) {
    return 0;
} else {
    return 10;
}
//建议修改为
return (isdone ? 0 : 10);
map、list伴随数据量越来越大,扩容很麻烦最好指定容量大小
//一般这么写
List<Integer> list = new ArrayList<>();
Map<String, String> map = new HashMap();

//集合默认容量较小,超过容量自动扩容,建议根据业务量、集合扩容规则等评估大概数据量n
List<Integer> list = new ArrayList<>(n);
Map<String, String> map = new HashMap(n);
//一般这么写
public void isFinished(Status status) {
   //可能抛空指针异常
return status.equals(Status.FINISHED); } //建议修改为 public void isFinished(Status status) { return Status.FINISHED.equals(status); } // public void isFinished(Status status) { return Objects.equals(status, Status.FINISHED); }

  MAX(id) 取最单id最大值,MAX() 全表扫描
SELECT MAX(id) from order o where o.pay_type = 23;
替代方案:
select id from order where pay_type = 23 order by id desc limit 1;
当偏移量很大当时候,先查询出9000条数据对应的主键id的值,然后直接通过该id的值直接查询该id后面的数据
select
* from sensor limit 9000,10; 替代方案: select * from sensor where id > (select id from sensor order by id limit 9000,1) limit 10;

 

posted @ 2020-08-07 16:22  你好。世界!  阅读(182)  评论(0)    收藏  举报