Groovy web console

subscribe to the feed Subscribe
to this
site
copyOfRange vs range subscript vs sublist (via #groovywebconsole)
tweet this snippet Tweet
this
script

copyOfRange vs range subscript vs sublist

Published 11 months ago by hlaaftana
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
import static java.lang.System.nanoTime as now
import groovy.transform.CompileStatic

@CompileStatic
def benchmark(int x = 2000, Closure a) {
    def sum = 0g
    x.times {
        def t = now()
        a()
        def u = now() - t
        sum += u
    }
    println sum / x
}

@CompileStatic
def z() {
    final Y = [1, 2, 3, 4, 5] as int[]

    benchmark { Arrays.copyOfRange Y, 0, 0 + 1 }
    benchmark { Y[0..0] }

    final Z = [1, 2, 3, 4, 5]

    benchmark { Z.subList(0, 0 + 1) }
    benchmark { Z[0..0] }
}
z()