I have an ExecutorService code snippet, and I am trying to convert it to coroutines in order to test performance. However no matter how I structure the coroutine code, ExecutorService is much faster. I thought that coroutines are supposed to improve performance
functionality:
- run in background thread
- execute 200000 actions (counter++)
- post time that passed to UI thread
- the code runs in a ViewModel updating a time text view
- executor service code take ~150 milliseconds on an emulator
- any coroutines code I wrote takes a lot longer
what would be the coroutine equivalent to the following code :
fun runCodeExecutorService() {
spinner.value = true
val executorService = Executors.newFixedThreadPool(NUMBER_OF_CORES * 2)
val result = AtomicInteger()
val startTime = System.currentTimeMillis()
val handler: Handler = object : Handler(Looper.getMainLooper()) {
override fun handleMessage(inputMessage: Message) {
time.value = toTime(System.currentTimeMillis() - startTime)
spinner.value = false
Log.d("tag", "counter Executor = " + result.get())
}
}
thread(start = true) {
for (i in 1..NUMBER_OF_THREADS) {
executorService.execute {
result.getAndIncrement()
}
}
executorService.shutdown();
executorService.awaitTermination(2, TimeUnit.MINUTES)
val msg: Message = handler.obtainMessage()
val bundle = Bundle()
bundle.putInt("MSG_KEY", result.get())
msg.data = bundle
handler.sendMessage(msg)
}
}
where NUMBER_OF_CORES is val NUMBER_OF_CORES = Runtime.getRuntime().availableProcessors()
NUMBER_OF_THREADS is 200000