![](/img/trans.png)
[英]Is it possible to compare two binary trees in less than O(n log n) time?
[英]Is it possible to make this nested for loop less than O(N^2)?
我正在使用Apache Spark 2.1和Java 8進行Kafka Streaming服務。我使用嵌套的for
循環用Topic / Partition對填充ArrayList
。
是否可以使用另一種方法從O(N ^ 2)減少此嵌套的for
循環?
這是代碼:
private static List<TopicAndPartition> createTAndPList(List<String> topics, List<String> partitions)
throws ConsumerException {
if (topics.size() != partitions.size()) {
throw new ConsumerException("Cannot create list with unequal number of topics and parititons,");
}
List<TopicAndPartition> topicsAndPartitions = new ArrayList<>();
for (int t = 0; t < topics.size(); t++) {
for (int p = 0; p < Integer.parseInt(partitions.get(t)); p++) {
topicsAndPartitions.add(new TopicAndPartition(topics.get(t), p));
}
}
return topicsAndPartitions;
}
僅供參考:由於無法控制的能力(管理),我無法在Kafka 8上使用。
使用您給定的代碼,似乎無法減少順序。
但是,您可以進行兩個小的優化。
將topic.get(t)從內部for循環中移出,
不要在每個循環中重新計算內部for循環終止條件。
for (int t = 0; t < topics.size(); t++) { String topic = topics.get(t); int count = Integer.parseInt(partitions.get(t)); for (int p = 0; p < count; p++) { topicsAndPartitions.add(new TopicAndPartition(topic, p));
您正在調用topic.get和Integer.parseInt(partitions.get(t)) t * p次,而不是t次。 對topic.get()的更改可能不會做很多事情,但是像這樣將某些內容移出內部循環是很常見的優化。
最后,您是否真的需要列表中的所有內容? 還是可以在實際需要它們的地方動態生成它們?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.