gpt4 book ai didi

java - 如何进一步优化代码?

转载 作者:行者123 更新时间:2023-11-30 11:01:11 24 4
gpt4 key购买 nike

祝大家今天愉快。

我的代码可以在几秒钟内完成 Excel Pivot 的功能。然而,我的代码在不少于 30 分钟内完成了同样的事情。我对差异感到震惊!我很确定我可以优化我的代码,使它比现在快得多。任何帮助将不胜感激。

请快速查看代码。如有必要,我将详细解释它到底做了什么。谢谢你!

public void countImages(ArrayList<String> all) throws IOException {
HashSet<String> uStrings = new HashSet<>();
int Counter = 0;
int C500x500 = 0;
int C800x800 = 0;
int C1000x1000 = 0;
int G1000x1000 = 0;
write("Vendor ID, Count of Images, Less than 500 x 500, Less than 800 x 800, Less than 1000 x 1000, Greater than 1000 x 1000", "ImageCount_Data");
for (String single : all) {
String[] linearray = single.split(",");
uStrings.add(linearray[0]);
}
totallines = uStrings.size();
completedlines = 0;
percentage = 0;
setPercent(0);
for (String uString : uStrings) {
Counter = 0;
C500x500 = 0;
C800x800 = 0;
C1000x1000 = 0;
G1000x1000 = 0;
for (String single : all) {
String[] linearray = single.split(",");
if (linearray[0].equals(uString)) Counter++;
if ((linearray[1].equals("Less than 500 x 500")) && linearray[0].equals(uString)) C500x500++;
if ((linearray[1].equals("Less than 800 x 800")) && linearray[0].equals(uString)) C800x800++;
if ((linearray[1].equals("Less than 1000 x 1000")) && linearray[0].equals(uString)) C1000x1000++;
if ((linearray[1].equals("Greater than 1000 x 1000")) && linearray[0].equals(uString)) G1000x1000++;
} //END OF 2ND FOR LOOP
write(uString + "," + Counter + "," + C500x500 + "," + C800x800 + "," + C1000x1000 + "," + G1000x1000, "ImageCount_Data");
completedlines++;
percentage = (completedlines / totallines) * 100;
setPercent(Math.round(percentage));
Icwindow.frame.setTitle("Writing Image Count Data: " + getPercent() + "%");
} //END OF 1ST FOR LOOP
Icwindow.frame.setTitle("Process Cloudinary ImageCount Data");
}

最佳答案

您正在遍历零列中所有可能的字符串,然后在该循​​环中再次遍历所有字符串。因此,您的算法是 O(n²),而 Excel 使用更快(可能是 O(n) 摊销)算法。

你可以使用 HashMap<String, Counts>仅使用一个 for 循环而不是两个嵌套循环来跟踪计数。

Counts然后对象将包含您的类的计数,如:

class Counts {
int c500;
int c800;
int c1000;
int cOther;

void count(String s) {
switch(s) {
case "Less than 500 x 500": c500++; break;
case "Less than 500 x 500": c800++; break;
case "Less than 500 x 500": c1000++; break;
case "Greater than 1000 x 1000": cOther++; break;
default: throw new AssertionError();
}
}
}

另一个提示:您可以通过添加 c500 + c800 + c1000 + cOther 来获取全局计数器.

关于java - 如何进一步优化代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31314378/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com