Skip to content

Optimize destructuring of array literals to elide intermediate array #23048

Closed

Description

@TimWolla

Description

The following code:

<?php

$a = 1;
$b = 2;

[$a, $b] = [$b, $a];

var_dump($a, $b);

currently compiles as:

$_main:
     ; (lines=14, args=0, vars=2, tmps=2)
     ; (after optimizer)
     ; test6.php:1-9
0000 ASSIGN CV0($a) int(1)
0001 ASSIGN CV1($b) int(2)
0002 T2 = INIT_ARRAY 2 (packed) CV1($b) NEXT
0003 T2 = ADD_ARRAY_ELEMENT CV0($a) NEXT
0004 T3 = FETCH_LIST_R T2 int(0)
0005 ASSIGN CV0($a) T3
0006 T3 = FETCH_LIST_R T2 int(1)
0007 ASSIGN CV1($b) T3
0008 FREE T2
0009 INIT_FCALL 2 112 string("var_dump")
0010 SEND_VAR CV0($a) 1
0011 SEND_VAR CV1($b) 2
0012 DO_ICALL
0013 RETURN int(1)
LIVE RANGES:
     2: 0003 - 0008 (tmp/var)

it should be optimized to something like:

0000 ASSIGN CV0($a) int(1)
0001 ASSIGN CV1($b) int(2)
0002 T1 = CV0($a)
0003 T2 = CV0($b)
0004 ASSIGN CV0($a) T2
0005 ASSIGN CV1($b) T1
0006 INIT_FCALL 2 112 string("var_dump")
0007 SEND_VAR CV0($a) 1
0008 SEND_VAR CV1($b) 2
0009 DO_ICALL
0010 RETURN int(1)

Activity

  1. ArtUkrainskiy commented on Oct 6, 2026

    @ArtUkrainskiy
    Contributor

    Hi Tim, I've tried this as a compile-time rewrite in zend_compile_assign() and it works — the swap goes from 922 to 467 instructions with the opcodes you describe — so I'll take it and open a PR.

  2. added 6 commits that reference this issue on Oct 7, 2026
    6ff9a1c
    df21459
    880d030
    e196d8c
    2ebf386
    1954448
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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