Last active
April 9, 2024 21:47
-
-
Save thospfuller/781b6c2f47b357f2cc032bfe8c98f253 to your computer and use it in GitHub Desktop.
Example Three: How to turn an array into an ArrayList in Java using Google Guava.
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 | |
@Grab(group='com.google.guava', module='guava', version='32.1.3-jre') | |
import static com.google.common.collect.Lists.newArrayList | |
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] = Integer.valueOf (random.nextInt()) | |
} | |
def iterations = 100000 | |
def monitor = MonitorFactory.start("Convert an array to an ArrayList performance monitor via Google Guava example") | |
for (ctr in 0..iterations) { | |
def exampleList = newArrayList (numbers) as java.util.List | |
} | |
monitor.stop () | |
println "iterations: $iterations, performance: $monitor" | |
return; |
With the requirement to autobox due to line #17 using a primitive int array (see line #28), the script will take ~166 seconds to run, on average, on my laptop. This number is not accurate however since autoboxing is an expensive operation. Once we've fixed this issue and retested we can see the time drops to ~3.7 seconds.
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!