Created
April 7, 2014 07:05
-
-
Save zakki/10015869 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// http://d.hatena.ne.jp/nowokay/20140330#1396177524 | |
import java.util.*; | |
import java.util.function.*; | |
import java.util.stream.*; | |
public class LoopBench2 { | |
public static void main(String[] args) { | |
List<Integer> list = IntStream.range(0, 100_000).boxed().collect(Collectors.toList()); | |
array = list.toArray(new Integer[0]); | |
for (int i = 0; i < 10; i++) { | |
bench("index", LoopBench2::index); | |
bench("forEach", LoopBench2::forEach); | |
bench("stream", LoopBench2::stream); | |
bench("intreduce", LoopBench2::intreduce); | |
bench("reduce", LoopBench2::reduce); | |
} | |
} | |
static Integer[] array; | |
static Integer forEach(){ | |
int c = 0; | |
for(Integer i : array){ | |
c += i; | |
} | |
return c; | |
} | |
static Integer index(){ | |
int c = 0; | |
for(int i = 0; i < array.length; ++i){ | |
c += array[i]; | |
} | |
return c; | |
} | |
static Integer stream(){ | |
int[] c = {0}; | |
Arrays.stream(array).forEach(i -> c[0] += i); | |
return c[0]; | |
} | |
static Integer reduce(){ | |
return Arrays.stream(array).collect(Collectors.summingInt(i -> i)); | |
} | |
static Integer intreduce(){ | |
return Arrays.stream(array).mapToInt(i -> i).sum(); | |
} | |
public static void bench(String name, Supplier<Integer> proc){ | |
bench(name, 50_000, proc); | |
} | |
public static void bench(String name, int count, Supplier<Integer> proc){ | |
for(int i = 0; i < 100; ++i){ | |
proc.get(); | |
} | |
long s = System.currentTimeMillis(); | |
for(int i = 0; i < count; ++i){ | |
proc.get(); | |
} | |
System.out.printf("%s(%d):%dms%n", name, proc.get(), System.currentTimeMillis() - s); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment