Skip to content
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

Memoization #179

Open
hediet opened this issue Dec 16, 2018 · 0 comments
Open

Memoization #179

hediet opened this issue Dec 16, 2018 · 0 comments
Labels
optimization 💪 New optimization feature
Projects
Milestone

Comments

@hediet
Copy link
Member

hediet commented Dec 16, 2018

Consider this code:

    public int fib(int n) {
        if(n < 2) {
            return n;
        }
        return fib(n - 1) + fib(n - 2);
    }

We could easily introduce memoization on side-effect free functions from int to int:

    fib_last_result: int;
    fib_last_arg: int;
    fib_last2_result: int;
    fib_last2_arg: int;

    public int fib(int n) {
        if (n == this.fib_last_arg) return this.fib_last_result;
        if (n == this.fib_last2_arg) return this.fib_last2_result;

        if(n < 2) {
            return n;
        }
        int result =fib(n - 1) + fib(n - 2);

        fib_last2_result = fib_last_result;
        fib_last2_arg = fib_last_arg);
        fib_last_arg = n; // ensure it hasn't changed
        fib_last_result = result;

        return result;
    }

We could even improve this if self-modifying code is allowed.

@hediet hediet added the optimization 💪 New optimization feature label Dec 16, 2018
@joshuabach joshuabach added this to the Optimizations milestone Jan 4, 2019
@problame problame added this to Todo Optimization in Endspurt Feb 4, 2019
@hediet hediet moved this from Todo Optimization to Stretch Goal in Endspurt Feb 4, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
optimization 💪 New optimization feature
Projects
Endspurt
  
Stretch Goal
Development

No branches or pull requests

2 participants