Created
November 4, 2019 21:18
-
-
Save juliofalbo/0f4db00834e31917b7e1c7cb24abdc30 to your computer and use it in GitHub Desktop.
PrimitiveTypes
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
/** | |
* In this operation we are doing 0 conversions, since we are working only with primitive type | |
*/ | |
private static void operationWithPrimitiveTypeFunctionInterface(){ | |
long startTime = System.currentTimeMillis(); | |
int[] array = initValues(); | |
IntPredicate predicate = i -> i % 2 == 0; | |
for(int primitive : array){ | |
if(predicate.test(primitive)){ | |
// System.out.println(primitive); | |
} | |
} | |
long stopTime = System.currentTimeMillis(); | |
long elapsedTime = stopTime - startTime; | |
System.out.println("ElapsedTime operationWithPrimitiveTypeFunctionInterface: " + elapsedTime); | |
} | |
/** | |
* In this operation we are doing 200000000 unintentionally conversions. | |
*/ | |
private static void operationWithWrapperClass(){ | |
long startTime = System.currentTimeMillis(); | |
int[] array = initValues(); | |
// Here we are doing (unintentionally) 100000000 conversions (auto-unboxing [Integer -> int]) | |
// since the type parameter of Predicate is Integer and we need to convert to int to make the math operation | |
Predicate<Integer> predicate = i -> i % 2 == 0; | |
for(int primitive : array){ | |
// Here we are doing (unintentionally) 100000000 conversions (autoboxing [int -> Integer]) since the type parameter of Predicate is Integer | |
if(predicate.test(primitive)){ | |
System.out.println(primitive); | |
} | |
} | |
long stopTime = System.currentTimeMillis(); | |
long elapsedTime = stopTime - startTime; | |
System.out.println("ElapsedTime operationWithWrapperClass: " + elapsedTime); | |
} | |
private static int[] initValues() { | |
int[] values = new int[100000000]; | |
Random random = new Random(); | |
for (int i = 0; i < values.length; i++) { | |
values[i] = random.nextInt(MAX_VALUE); | |
} | |
return values; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment