0

Iterating has bad performance after sort.

Here is my code

method() {
    var time = System.currentTimeMillis()
    arraylist = ArrayList<Float>()
    for(i in 1..1000000){
        arraylist.add(Math.random().toFloat())
    }
    Log.i("TIME", (System.currentTimeMillis() - time).toString())

    for(i in 1..5){
        time = System.currentTimeMillis()
        for(a in arraylist){
            //nothing
        }
        Log.i("TIME To Iterate", (System.currentTimeMillis() - time).toString())
    }


    arraylist.sort()

    for(i in 1..5){
       time = System.currentTimeMillis()
        for(a in arraylist){
                //nothing
        }
           Log.i("TIME To Iterate", (System.currentTimeMillis() - time).toString())
        }

    }
}

Here is a result

Result

Result said iterating performance be lower after sorting

Why iterating performance is lowered when sorting?

  • Your code is neither valid Java nor valid Kotlin code. Please amend it to be executable. – lukas.j Dec 02 '21 at 09:39
  • [Please do not upload images of results when asking a question.](//meta.stackoverflow.com/q/285551) – gidds Dec 02 '21 at 17:53
  • 1
    Also, the code you have (if it works) is nowhere near enough to warm up the JVM, cause code to be JIT compiled, &c &c, and so the timings are highly unlikely to be representative of anything. Please see the various questions on this site about microbenchmarking. (For one thing, it wouldn't surprise me if the runtime eventually optimised out those empty loops entirely.) – gidds Dec 02 '21 at 17:56
  • Also, if you want to measure the time that it took your code to execute, you can use Kotlin's `measureTimeMillis` function. – michaelgrigoryan25 Dec 05 '21 at 19:35

0 Answers0