为什么这两段代码在相同条件下运行,运行时间没有差异?
代码 1
static long time = 0;
static int n = 200;
static float[] vq = new float[200 * 200 * 200 * 3];
static int[] iq = new int[200 * 200 * 200];
static FloatBuffer verts = BufferUtils.createFloatBuffer(vq.length);
static IntBuffer ind = BufferUtils.createIntBuffer(iq.length);
static void draw() {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
for (int k = 0; k < n; k++) {
int index = (i * n * n) + (j * n) + k;
vq[3 * index + 0] = i;
vq[3 * index + 1] = j;
vq[3 * index + 2] = k;
iq[index] = index;
}
}
}
verts.put(vq);
ind.put(iq);
verts.flip();
ind.flip();
GL11.glEnableClientState(GL11.GL_VERTEX_ARRAY);
GL11.glVertexPointer(3, 0, verts);
GL11.glDrawElements(GL11.GL_QUADS, ind);
GL11.glDisableClientState(GL11.GL_VERTEX_ARRAY);
long newTime = System.currentTimeMillis();
System.out.println(newTime - time);
time = newTime;
}
代码 2
static int n = 200;
static long time = 0;
static void draw() {
GL11.glBegin(GL11.GL_QUADS);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
for (int k = 0; k < n; k++) {
GL11.glVertex3f(i, j, k);
}
}
}
GL11.glEnd();
long newTime = System.currentTimeMillis();
System.out.println(newTime - time);
time = newTime;
}
我认为Code 2应该比Code1慢的原因是它有近 800 万个本机调用,但Code 1只有几个,它们在结果中做同样的事情。
原因是什么,如何提高代码的性能?