Skip to content

Instantly share code, notes, and snippets.

@netzwerg
Created January 24, 2016 11:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save netzwerg/4646e22e1675b01b1231 to your computer and use it in GitHub Desktop.
Save netzwerg/4646e22e1675b01b1231 to your computer and use it in GitHub Desktop.
Using RC3, imperative variant is 2x faster (800 ms vs. 1800 ms), GC going nuts with all the tuples...
import javaslang.collection.Stream;
import org.junit.Test;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static org.junit.Assert.assertEquals;
public class ZipWithIndexTest {
private static final java.util.List<String> JAVA_LIST = IntStream.range(0, 1_000_000).mapToObj(String::valueOf).collect(Collectors.toList());
private static final java.lang.Iterable<String> JAVA_ITERABLE = JAVA_LIST::iterator;
@Test
public void functional() {
long startTime = System.currentTimeMillis();
Stream<String> result = Stream.ofAll(JAVA_ITERABLE).zipWithIndex().map(t -> {
long index = t._2;
String s = t._1;
return s + index;
});
assertEquals(1_000_000, result.size());
System.out.println("Functional variant: " + (System.currentTimeMillis() - startTime));
}
@Test
public void imperative() {
long startTime = System.currentTimeMillis();
AtomicLong indexRef = new AtomicLong();
Stream<String> result = Stream.ofAll(JAVA_ITERABLE).map(s -> {
long index = indexRef.getAndIncrement();
return s + index;
});
assertEquals(1_000_000, result.size());
System.out.println("Imperative variant: " + (System.currentTimeMillis() - startTime));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment