Skip to content

Reduce frequency of checkcast in bytecode #1377

@scabug

Description

@scabug

When we use "def = new { ... }",
the generated bytecode appears to have too little type information, and too many casts. Same for "val", and for "new with { ... }"

Here's a minimal example:-

trait B

trait C

final class Test {
    def d1 = new B {} // return type java.lang.Object in bytecode
    def d3: B = new B {}

    val v1 = d1 // java.lang.Object in bytecode
    val v2: B = d1 // uses checkcast
    val v3: B = d3

    def f(x: B) {}

    f(v1) // uses checkcast
    f(v2)
    f(v3)
}

// If we change "B" to "B with C", the java.lang.Object and checkcast still occur

A real-world example is the trait Iterator, and the Iterator members

    val empty
    def single
    def range
    def append
    def ++
    def zip
    def zipWithIndex

None of these explicitly declare the return type, so java.lang.Object and checkcast occur.

Here's an informal benchmark that shows the impact this can have on performance:

object T7 {
    def f(i: Iterator[_]) = i.hasNext

    def main(args: Array[String]) {

        val empty = Iterator.empty // checkcast occurs within loop, program takes 26s
        // val empty: Iterator[_] = Iterator.empty // checkcast outside loop, program takes 22s

        for (i <- 1 to 1000000000) {
            f(empty)
        }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions