Skip to content

Fix #23224: Optimize simple tuple extraction #23373

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

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from

Conversation

noti0na1
Copy link
Member

@noti0na1 noti0na1 commented Jun 16, 2025

Fix #23224:

This PR optimizes simple tuple extraction by avoiding unnecessary tuple allocations and refines the typing of bind patterns for named tuples.

  • Update typedBind to use pt if the pattern is named tuple.
  • Optimise makePatDef to reduce tuple creation when a pattern uses only simple variables or wildcards.

For example:

def f1: (Int, Int, Int) = (1, 2, 3)
def test1 =
  val (a, b, c) = f1
  a + b + c

Before this PR:

val $1$: (Int, Int, Int) =
  this.f1:(Int, Int, Int) @unchecked match 
    {
      case Tuple3.unapply[Int, Int, Int](a @ _, b @ _, c @ _) =>
        Tuple3.apply[Int, Int, Int](a, b, c)
    }
val a: Int = $1$._1
val b: Int = $1$._2
val c: Int = $1$._3
a + b + c

After this PR:

val $2$: (Int, Int, Int) =
  this.f1:(Int, Int, Int) @unchecked match 
    {
      case $1$ @ Tuple3.unapply[Int, Int, Int](_, _, _) =>
        $1$:(Int, Int, Int)
    }
val a: Int = $2$._1
val b: Int = $2$._2
val c: Int = $2$._3
a + b + c

Also in genBCode now:

val $2$: Tuple3 =  
  matchResult1[Tuple3]:
    {
      case val x1: Tuple3 = this.f1():Tuple3
      if x1 ne null then
        {
          case val $1$: Tuple3 = x1
          return[matchResult1] $1$:Tuple3
        }
        else ()
      throw new MatchError(x1)
    }
val a: Int = Int.unbox($2$._1())
val b: Int = Int.unbox($2$._2())
val c: Int = Int.unbox($2$._3())
a + b + c

I use the regular expression (val\s*\(\s*[a-zA-Z_]\w*(\s*,\s*[a-zA-Z_]\w*)*\s*\)\s*=) to search in the compiler, and found 400+ places which are simple tuple extraction like this.

@noti0na1 noti0na1 requested a review from Copilot June 16, 2025 00:23
Copilot

This comment was marked as resolved.

@noti0na1
Copy link
Member Author

Split some change into a separate PR #23380 to diagnose the errors.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Optimise simple tuple extraction
1 participant