我有一个包含大约 700 个或更多任务的任务列表。我正在尝试使用以下代码通过
taskId
进行搜索。它可以工作,但需要很长时间 - 大约 1 分钟。列表未排序。
List<Tasks> tasks = ....;
tasks = tasks
.stream()
.filter(task -> task.getTaskId().equals("1000"))
.collect(Collectors.toList());
循环任务花费的时间几乎相同。
如何增强我的代码以加快速度?
在我的系统上,打印以下示例:
Filtering 700 records took 10210465ns and found 69 matches.
与您的 1 分钟相比,这是 10 毫秒。 (JIT 编译器将没有机会完全启动。)
使用分析器找出应用程序中的时间花费在哪里。我怀疑你的
getTaskID
方法的作用比你想象的要多。
public class Filter {
static Random rng = new Random();
static record Task(String id){};
public static void main(String[] args) {
int howMany = 700;
List<Task> tasks = makeTasks(howMany, 0.1f);
long before = System.nanoTime();
tasks = tasks
.stream()
.filter(task -> task.id().equals("1000"))
.collect(Collectors.toList());
long after = System.nanoTime();
System.out.println("Filtering "+howMany+" records took "+(after-before)+"ns and found "+tasks.size()+" matches.");
}
static List<Task> makeTasks(int howMany, float probabilityOfMatch) {
var list = new ArrayList<Task>(howMany);
for (int i = 0; i < howMany; i++) {
var id = Integer.toString((rng.nextFloat() < probabilityOfMatch ? 1000 : i));
list.add(new Task(id));
}
Collections.shuffle(list);
return list;
}
}