Skip to content

Inefficient code generated for if used as statement #5750

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
smarter opened this issue Jan 19, 2019 · 0 comments
Closed

Inefficient code generated for if used as statement #5750

smarter opened this issue Jan 19, 2019 · 0 comments

Comments

@smarter
Copy link
Member

smarter commented Jan 19, 2019

Given:

class A
object Test {
  def doStuff(): String = ""
  def test(cond: Boolean): Int = {
    if (cond) {
      doStuff()
    }
    1
  }
}

The generated code for test is:

         0: iload_1
         1: ifeq          11
         4: aload_0
         5: invokevirtual #22                 // Method doStuff:()Ljava/lang/String;
         8: goto          14
        11: getstatic     #28                 // Field scala/runtime/BoxedUnit.UNIT:Lscala/runtime/BoxedUnit;
        14: pop
        15: iconst_1
        16: ireturn

Which is basically equivalent to val a = if (cond) doStuff() else BoxedUnit.UNIT; 1. More efficient bytecode is generated if the if branch ends with ():

class A
object Test {
  def doStuff(): String = ""
  def test(cond: Boolean): Int = {
    if (cond) {
      doStuff()
      ()
    }
    1
  }
}
         0: iload_1
         1: ifeq          9
         4: aload_0
         5: invokevirtual #24                 // Method doStuff:()Ljava/lang/String;
         8: pop
         9: iconst_1
        10: ireturn

It shouldn't be too complicated to emit this for the original example too (either with a better analysis in the backend or with a tree transformation phase that adds the () to ifs that are not used as expression. Note that scalac seems to behave exactly like dotty here /cc @retronym @lrytz

allanrenucci added a commit to dotty-staging/dotty that referenced this issue Jan 19, 2019
allanrenucci added a commit to dotty-staging/dotty that referenced this issue Jan 19, 2019
odersky added a commit that referenced this issue Jan 20, 2019
Fix #5750: Type then part of If with no else part as Unit
allanrenucci added a commit to dotty-staging/dotty that referenced this issue Jan 21, 2019
allanrenucci added a commit to dotty-staging/dotty that referenced this issue Jan 21, 2019
allanrenucci added a commit to dotty-staging/dotty that referenced this issue Jan 21, 2019
allanrenucci added a commit to dotty-staging/dotty that referenced this issue Jan 21, 2019
allanrenucci added a commit to dotty-staging/dotty that referenced this issue Jan 21, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant