Skip to content

Constant fold enum member initializers. #917

Closed

Description

Consider the following enum definition:

enum Flags {
    A = 1,
    B = 2,
    C = A | B // Should be constant folded to 3.
}

In most cases, JS engines can optimize simple expressions like these. But they can't do much about accesses to Flags.C.

switch (x) {
  case Flags.A: ... break; // Compiled as case 1: ...
  case Flags.B: ... break; // Compiled as case 2: ...
  case Flags.C: ... break; // Compiled as Flags.C: ...  
}

This prevents JS engines from using a table jump and causes them to fall back on a sequential if/else if implementation for the switch which is all sorts of terrible.

Activity

  1. RyanCavanaugh commented on Oct 18, 2014

    @RyanCavanaugh
    Member

    We've talked about this before as something we'd like to do -- the old compiler would do this under an experimental flag and it was nice for a small perf boost. This also would be a necessary first step for a "zero emit" enum that some we had interest in.

    As a rough outline I'd expect this to support math over |, &, ~, +, -, integer literals, and previously-declared enum members.

  2. DanielRosenwasser commented on Oct 25, 2014

    @DanielRosenwasser
    Member

    I think I'll take this on.

  3. vladima commented on Oct 25, 2014

    @vladima
    Contributor

    Oops, I've already started working on this one.


    From: Daniel Rosenwassermailto:notifications@github.com
    Sent: ý10/ý25/ý2014 11:22 AM
    To: Microsoft/TypeScriptmailto:TypeScript@noreply.github.com
    Subject: Re: [TypeScript] Constant fold enum member initializers. (#917)

    I think I'll take this on.

    —
    Reply to this email directly or view it on GitHubhttps://github.com//issues/917#issuecomment-60491992.

  4. DanielRosenwasser commented on Oct 25, 2014

    @DanielRosenwasser
    Member

    Oops 😄 - I currently propagate arithmetic ops on constants but not previously declared enums. You're probably farther than me, right?

  5. vladima commented on Nov 4, 2014

    @vladima
    Contributor

    covered by #970

  6. locked and limited conversation to collaborators on Jun 18, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    FixedA PR has been merged for this issueHelp WantedYou can do thisIn DiscussionNot yet reached consensusSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions