在编码过程中要避免在循环中查询数据库,能一次查询的就不要多次查询。下面两个代码块是完全等效的。代码块一写起来简单,但却在循环中多次查询数据库,该代码执行时间为8毫秒。代码二写起来麻烦甚至还多了个双重循环,但只查询一次数据库,该代码执行时间为2毫秒。
代码块一:
for (Device dev : list) {
String dmi = dev.getDeviceModelId();
if (StringUtils.isBlank(dmi)){
continue;
}
DeviceModel dm = this.deviceModelManager.get(dmi); //查询数据库
dev.setDeviceModel(dm);
}
代码块二:
List<String> deviceModelIdList = new ArrayList<String>();
for (Device dev : list) {
String dmi = dev.getDeviceModelId();
if (StringUtils.isBlank(dmi)){
continue;
}
deviceModelIdList.add(dmi);
}
List<DeviceModel> deviceModelList = this.deviceModelManager.find(new NameValuePair("id", MatchMode.IN, deviceModelIdList)); //查询数据库
for (Device dev : list) {
for(DeviceModel model : deviceModelList){
if(model.getId().equals(dev.getDeviceModelId())){
dev.setDeviceModel(model);
}
}
}