Java 阵列列表优化
我目前正在进行此项工作,以满足个人需求,并希望获得一些关于如何加快此代码的建议: 我有一个由对象注释组成的ArrayList,其中存储了坐标和颜色值 在渲染调用期间实时创建每个“注释” 我做了这个功能:Java 阵列列表优化,java,for-loop,arraylist,processing,Java,For Loop,Arraylist,Processing,我目前正在进行此项工作,以满足个人需求,并希望获得一些关于如何加快此代码的建议: 我有一个由对象注释组成的ArrayList,其中存储了坐标和颜色值 在渲染调用期间实时创建每个“注释” 我做了这个功能: void keyPressed() { if (key == 's' || key == 'S') { PImage img = createImage(posX, specSize, RGB); for(int x = 0; x < posX;
void keyPressed() {
if (key == 's' || key == 'S') {
PImage img = createImage(posX, specSize, RGB);
for(int x = 0; x < posX; x++){
for(int y = 0; y < specSize; y++){
for(int i = 0; i < notes.size(); i++){
if( (notes.get(i).getX() == x)
&& (notes.get(i).getY() == y) ){
int loc = x + y*posX;
img.pixels[loc] = color(notes.get(i).getR(),
notes.get(i).getG(), notes.get(i).getB());
}
}
}
}
img.updatePixels();
img.save("outputImage.png");
}
}
void键按下(){
如果(键=='s'| |键=='s'){
PImage img=createImage(posX、specSize、RGB);
对于(int x=0;x
因此,当我按下“S”键时,我在宽度和高度上运行一个循环,因为它们在每次运行中都可能不同,然后在我的arrayList上,得到对应的“注释”,以及它的x和y位置。
然后我写我的图片文件。
你可以想象,这真的,真的,很慢1976x256px文件大约需要5到6分钟。 对我来说没关系,但如果能缩短一点就好了 有没有办法优化这三个循环? 如果您需要更多的代码,请告诉我这是一个小代码,我不介意。这个怎么样
void keyPressed() {
if (key == 's' || key == 'S') {
PImage img = createImage(posX, specSize, RGB);
for(int i = 0; i < notes.size(); i++){
int x = notes.get(i).getX();
int y = notes.get(i).getY();
int loc = x + y*posX;
img.pixels[loc] = color(notes.get(i).getR(),
notes.get(i).getG(), notes.get(i).getB());
}
img.updatePixels();
img.save("outputImage.png");
}
}
可以克隆notes(以及用于保存的任何其他对象),并在不同的线程中执行此操作,以便与UI异步。代码将花费相同或更多的时间,但用户可以使用应用程序的其余部分。克隆是必要的,因为您需要单击“保存”时的状态快照
不要让线程被放置使用线程池执行器,最大线程数为一个。在run方法中,可以应用David建议的方法-一个循环而不是两个循环。将注释列表转换为如下映射的结构
Map创建一个类,例如具有x
和y
两个属性的Point,并实现适当的equals和hashcode方法,如下所示:
public class Point {
private final int x;
private final int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Point point = (Point) o;
if (x != point.x)
return false;
if (y != point.y)
return false;
return true;
}
@Override
public int hashCode() {
int result = x;
result = 31 * result + y;
return result;
}
}
现在把这个点作为一个映射的键,用它来找到你的点,这样你就不必重复整个列表。好吧,咖啡休息后,我也这么想:),除了你的语法更好。但在另一个主题上,我的渲染速度非常慢,在OpenGL2.0中,但每个音符都渲染一条线,但我无法实现更快的渲染。(我对stack还是个新手,我不知道我是否必须用你的答案编辑第一篇帖子,如果你能帮忙的话,我是否可以在这里问一个新问题,或者问一个新的主题:))我认为你应该把它作为一个新问题来问,但可能会在其中包含一个指向这个问题的链接。
public class Point {
private final int x;
private final int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Point point = (Point) o;
if (x != point.x)
return false;
if (y != point.y)
return false;
return true;
}
@Override
public int hashCode() {
int result = x;
result = 31 * result + y;
return result;
}
}