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

perf: Add benchmark and speedup #37

Merged
merged 18 commits into from
Feb 1, 2024
10 changes: 10 additions & 0 deletions bench/fib.lox
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
fun fib(n) {
if (n < 2) return n;
return fib(n - 1) + fib(n - 2);
}

var before = clock();
print fib(40);
var after = clock();
print "Time elapsed (ms):";
print after - before;
10 changes: 10 additions & 0 deletions bench/fib33.lox
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
fun fib(n) {
if (n < 2) return n;
return fib(n - 1) + fib(n - 2);
}

var before = clock();
print fib(33);
var after = clock();
print "Time elapsed (ms):";
print after - before;
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"README.md"
],
"scripts": {
"benchmark": "pnpm --silent run repl bench/fib33.lox",
"build": "tsup",
"coverage": "pnpm test -- --coverage --no-watch",
"format": "prettier \"**/*\" --ignore-unknown",
Expand Down
6 changes: 4 additions & 2 deletions src/interpreter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,9 @@ import { CurrencyValue, LoxValue, isCurrency } from "./lox-value.js";
import { runtimeError } from "./main.js";
import { Token } from "./token.js";

export class ReturnCall extends Error {
export class ReturnCall {
value: LoxValue;
constructor(value: LoxValue) {
super();
this.value = value;
}
}
Expand Down Expand Up @@ -286,6 +285,9 @@ export class Interpreter {

case "return": {
const value = stmt.value && this.evaluate(stmt.value);
// While it's bad practice to throw something other than an Error subclass,
// doing so here result in a ~5x speedup on the Fibonacci benchmark.
// eslint-disable-next-line @typescript-eslint/no-throw-literal
throw new ReturnCall(value);
}

Expand Down
Loading