Last active
April 9, 2024 22:28
-
-
Save thospfuller/2433f04d4f5af0872b83c2cd5a5b24e7 to your computer and use it in GitHub Desktop.
Example Zero: How to convert an array to an ArrayList in Java using the constructor.
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
@Grab(group='com.jamonapi', module='jamon', version='2.82') | |
import com.jamonapi.Monitor | |
import com.jamonapi.MonitorFactory | |
import static java.util.Arrays.asList | |
import java.util.stream.Collectors; | |
import java.util.List; | |
import java.util.Arrays; | |
import java.util.Random | |
def random = new Random() | |
def arrayCapacity = 10000 | |
def numbers = new java.lang.Integer[arrayCapacity + 1] | |
for (int ctr in 0..arrayCapacity) { | |
numbers[ctr] = java.lang.Integer.valueOf(random.nextInt()) | |
} | |
def iterations = 100000 | |
def monitor = MonitorFactory.start("Convert an array to an ArrayList performance monitor via the constructor example") | |
for (ctr in 0..iterations) { | |
def tempResult = asList (numbers) | |
def result = new java.util.ArrayList (tempResult) as java.util.List | |
} | |
monitor.stop () | |
println "iterations: $iterations, performance: $monitor" | |
return; |
Note that the previous version of this script used a primitive int, which caused autoboxing to take place on line 28. This update removes the autoboxing requirement by creating an array of type java.lang.Integer on line 16.
Performance with autoboxing: ~179.3 seconds
Performance without autoboxing: ~ 721.8 ms
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See the following article: How To Convert An Array To An ArrayList In Java!