Skip to content

Commit

Permalink
perf: Add benchmark and speedup (#37)
Browse files Browse the repository at this point in the history
Fixes #36 at least to some extent!

Throwing a non-`Error` subclass makes the Fibonacci benchmark ~6x
faster:

    -Time elapsed (ms): 60459
    +Time elapsed (ms): 10152

The difference for the 40th Fibonacci number is even more dramatic,
~2000s → 200s. Still slower than jlox's 27 seconds, but at least within
an order of magnitude.

Thanks to https://github.com/davidhfriedman/jslox for the inspiration.
  • Loading branch information
danvk committed Feb 1, 2024
1 parent 452b67f commit a9b73bd
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 2 deletions.
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

0 comments on commit a9b73bd

Please sign in to comment.