While it could be suggested that Parallel.For is simular to ExecutorService.submit, I suspect it is not.
public static void main(String... args) throws InterruptedException {
long start1 = System.nanoTime();
int runs1 = 1000;
final int[] a = new int[100];
for (int j = 0; j < runs1; j++) {
for (int i = 0; i < 100; i++) {
a[i] = a[i] * a[i];
}
}
long time1 = System.nanoTime() - start1;
System.out.printf("Each loop took an average of %,d micro-seconds%n", time1 / runs1 / 1000);
int processors = Runtime.getRuntime().availableProcessors();
long start2 = System.nanoTime();
ExecutorService executor = Executors.newFixedThreadPool(processors);
for (int j = 0; j < runs1; j++) {
for (int i = 0; i < 100; i++) {
final int i2 = i;
executor.submit(new Runnable() {
public void run() {
a[i2] = a[i2] * a[i2];
}
});
}
}
executor.shutdown();
executor.awaitTermination(1, TimeUnit.SECONDS);
long time2 = System.nanoTime() - start2;
System.out.printf("Parallel: Each loop took an average of %,d micro-seconds%n", time2 / runs1 / 1000);
}
prints
Each loop took an average of 2 micro-seconds
Parallel: Each loop took an average of 149 micro-seconds
This shows that in this example, using multiple threads is a very bad idea. So I would hope that the loop is the slightly more efficient
for (int j = 0; j < runs1; j++) {
for (int i = 0; i < processors; i++) {
final int i2 = i;
executor.submit(new Runnable() {
public void run() {
for (int i3 = i2 * 100 / processors; i3 < (i2 + 1) * 100 / processors && i3 < 100; i3++)
a[i2] = a[i2] * a[i2];
}
});
}
}
prints
Parallel: Each loop took an average of 28 micro-seconds
If you consider that the code in the Runnable is not thread safe, I suspect Parallel.For does something rather different or its pretty pointless.