查找性能提升:从文件到缓存,从顺序查找到二分查找

/**
* 通过模型编码从csv文件中读取模型属性
*/
public static void getModelAttribute(String strBianma){
File fCSV= new File("E:\\Data\\model.csv");//CSV文件路径
boolean flag=false;
try
{
BufferedReader br = new BufferedReader(new FileReader(fCSV));
String line;
while((line=br.readLine())!=null){
String[] strAttribute = line.split(",");
int intEnd=strAttribute[0].indexOf("|");
String bianma = strAttribute[0].substring(0, intEnd);
if(bianma.equals(strBianma)){
modelName = strAttribute[1];
modelHeight = Float.parseFloat(strAttribute[4]);
flag=true;
break;
}
}
br.close();
} catch (Exception ex) {
ex.printStackTrace();
}
if(flag==false){
modelName = null;
modelHeight = 0;
}
}
通过文件进行查找所需时间平均为247毫秒
/**
* 通过模型编码从csv文件中读取模型属性
*/
public static void getModelAttribute(String strBianma){
File fCSV= new File("E:\\Data\\model.csv");//CSV文件路径
boolean flag=false;
try
{
BufferedReader br = new BufferedReader(new FileReader(fCSV));
String line;
while((line=br.readLine())!=null){
String[] strAttribute = line.split(",");
int intEnd=strAttribute[0].indexOf("|");
String bianma = strAttribute[0].substring(0, intEnd);
if(bianma.equals(strBianma)){
modelName = strAttribute[1];
modelHeight = Float.parseFloat(strAttribute[4]);
flag=true;
break;
}
}
br.close();
} catch (Exception ex) {
ex.printStackTrace();
}
if(flag==false){
modelName = null;
modelHeight = 0;
}
}

/**
* 从csv文件中读取模型属性,将其放到缓存中,提高处理速度(以空间换取时间)
*/
public static void setModelAttribute(String csv){
File fCSV= new File(csv);//CSV文件路径
try
{
BufferedReader br = new BufferedReader(new FileReader(fCSV));
String line;
while((line=br.readLine())!=null){
modelAttribute.add(line);
}
br.close();
System.out.println("模型总数为:"+modelAttribute.size());
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* 从缓存中查找模型属性
*/
public static void searchModelAttribute(String strBianma){
boolean flag=false;
for(int i=0; i < modelAttribute.size(); i++){
String[] strAttribute = modelAttribute.get(i).split(",");
int intEnd=strAttribute[0].indexOf("|");
String bianma = strAttribute[0].substring(0, intEnd);
if(bianma.equals(strBianma)){
modelName = strAttribute[1];
modelHeight = Float.parseFloat(strAttribute[4]);
flag=true;
break;
}
}
if(flag==false){
modelName = null;
modelHeight = 0;
}
}
通过缓存进行查找所需时间平均为81毫秒(节省了2/3的时间)

/**
*通过递归进行二分查找
* */
public static int BinarySearch(String strBianma, int low, int high)
{
int mid = low+(high-low)/2;
String[] sMid=modelAttribute.get(mid).split(",");
int i=isMoreThan(sMid[0],strBianma+"|");
if(i==0){
return mid;
}
else if(i>0){
return BinarySearch(strBianma, low, mid-1);
}
else{
return BinarySearch(strBianma,mid+1,high);
}
}
通过二分查找法,性能进一步提升,查找时间几乎可以忽略不计

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值