Korr

Node.js vs PHP vs Python vs Korr

Docs index

This guide lists the everyday features of Node.js (JavaScript), PHP 8 and Python 3, shows how each one writes them, which approach Korr adopted and why, what Korr adds that the others do not have built in, and, honestly, what Korr does not have yet.

Legend: Yes: built in. Partial: possible but limited or needs care. No: not built in (needs a library or not possible).

Contents: Summary matrix  
Feature-by-feature  
What only Korr has built in  
Not in Korr yet Performance

Summary matrix

# Feature Node.js PHP Python Korr
1 Variables / constants Yes: let const Yes: $x, const Partial: no real constants Yes: let const (checked at compile time)
2 Undefined names caught before running No No No Yes
3 String interpolation Yes: `${x}` Partial: "$x", "{$x}" (vars only) Yes: f"{x}" Yes: "{x}" (any expression)
4 Multi-line strings with auto-dedent No Yes: heredoc No (textwrap.dedent) Yes: """..."""
5 Strict types (no "1" + 1) No No Yes Yes
6 Integer overflow safety No: loses precision No: silently becomes float Yes: big ints Yes: raises OverflowError
7 Arrays / lists Yes Yes Yes Yes
8 Ordered maps / dicts Yes: objects/Map Yes: arrays Yes: dict Yes: map
9 Destructuring Yes Yes: [$a, $b] = Partial: sequences only Yes: arrays + maps
10 Spread / rest Yes: ... Yes: ... Yes: * ** Yes: ...
11 List comprehensions No No Yes Yes
12 Slicing with negative indexes Partial: .slice() Partial: array_slice Yes: a[1:3] Yes: a[1..3], a[-2..]
13 Null coalescing ?? Yes Yes No Yes
14 Optional chaining ?. Yes Yes: ?-> No Yes
15 Ternary Yes Yes Yes: a if c else b Yes: c ? a : b
16 Pattern matching No Partial: match (values only) Yes: match (3.10+) Yes: match (values, ranges, guards, arrays)
17 Pipe operator No Yes: \|> (8.5+) No Yes: \|>
18 Default parameters Yes Yes Yes Yes
19 Named arguments No Yes Yes Yes
20 Variadic parameters Yes Yes Yes Yes
21 Closures / lambdas Yes Yes Partial: one-expression lambda Yes
22 Classes / structs Yes: class Yes: class Yes: class Yes: struct + impl
23 Inheritance / interfaces Yes Yes Yes No (composition; traits planned)
24 Exceptions with finally Yes Yes Yes Yes
25 Modules Yes: ESM Partial: require + namespaces Yes Yes: import "./x.krr" as x
26 Type hints enforced at runtime No (TypeScript is compile-only) Yes No (not enforced) Yes: optional
27 JSON Yes Yes Yes Yes
28 File system Yes Yes Yes Yes
29 HTTP server with routing Partial: server only (Express for routing) Partial: needs Apache/Nginx+FPM (php -S is dev-only) Partial: http.server, no routing (Flask/FastAPI) Yes: built in
30 Auto-escaping HTML templates No (framework) No (Twig/Blade) No (Jinja2) Yes: html"..."
31 Secure response headers by default No (helmet) No No Yes
32 CLI args / env / exit codes Yes Yes Yes Yes
33 Shell-free subprocess by default Partial: execFile (but exec uses a shell) No: exec uses a shell Yes: subprocess.run([...]) Yes: only shell-free
34 Password hashing API Partial: crypto.scrypt Yes: password_hash Partial: hashlib.pbkdf2_hmac Yes: crypto.hash_password
35 Built-in test runner Yes: node:test No (PHPUnit) Yes: unittest Yes: korr test
36 Single-file executable Partial: SEA (multi-step) No No (PyInstaller) Yes: korr build
37 REPL Yes Yes: php -a Yes Yes
38 async / await Yes Partial: Fibers Yes: asyncio No: planned
39 Generators / yield Yes Yes Yes No: planned
40 Regular expressions Yes Yes Yes Yes: re (linear time)
41 Database access Partial: node:sqlite Yes: PDO Yes: sqlite3 Yes: db: SQLite, PostgreSQL, MySQL
42 Package manager Yes: npm Yes: Composer Yes: pip Yes: korr add (Git-based, lock file; no central registry)
43 HTTP client Yes: fetch Yes: curl Yes: urllib Yes: http.get/post/fetch
44 Threads / parallelism Yes: workers Partial Yes Partial: server workers (app.listen(port, { workers: n })), no threads in programs
45 Structured logging Partial: console (pino/winston) Partial: error_log (Monolog) Yes: logging Yes: log (text/JSON)
46 CSV No (csv-parse) Yes: fgetcsv Yes: csv Yes: csv
47 .env files Yes: --env-file No (vlucas/phpdotenv) No (python-dotenv) Yes: os.load_env()

Feature-by-feature

Each section shows the four languages, then Korr’s choice: the approach Korr judged clearest and safest.

1. Variables and constants

// Node.js
let count = 0;
const MAX = 10;
<?php
$count = 0;
const MAX = 10;
# Python
count = 0
MAX = 10   # only a naming convention; it can still be changed
let count = 0
const MAX = 10

Korr’s choice: JavaScript’s let/const (explicit declaration, no $), plus a compile-time check that MAX = 11 is impossible and that cuont = 1 (a typo) is an error instead of silently creating a new variable as in Python or PHP.

2. Strings and interpolation

const msg = `Hello ${user.name}, you have ${items.length} items`;
const block = `
  <p>indentation is kept</p>`;
<?php
$msg = "Hello {$user['name']}, you have " . count($items) . " items";
$block = <<<HTML
    <p>closing marker indentation is removed</p>
    HTML;
msg = f"Hello {user['name']}, you have {len(items)} items"
block = """
  <p>indentation is kept</p>"""
// no-check
let msg = "Hello {user.name}, you have {len(items)} items"
let block = """
    <p>indentation is removed automatically</p>
    """

Korr’s choice: Python’s f-strings without the f prefix: every double-quoted string can interpolate any expression; single quotes are literal. Multi-line strings dedent automatically like PHP’s flexible heredoc.

3. Numbers and arithmetic

Operation Node.js PHP Python Korr
7 / 2 3.5 3.5 3.5 3.5
floor division Math.floor(7 / 2) intdiv(7, 2) 7 // 2 math.div(7, 2)
power 2 ** 10 2 ** 10 2 ** 10 2 ** 10
9007199254740993 loses precision ok ok ok
PHP_INT_MAX + 1 / i64::MAX + 1 n/a silently a float ok (big int) OverflowError
1 / 0 Infinity DivisionByZeroError ZeroDivisionError ZeroDivisionError

Korr’s choice: Python’s semantics for / (always float) and for errors on division by zero. Integers are fast 64-bit values that fail loudly on overflow rather than silently changing type (PHP) or precision (JavaScript). Python’s unlimited integers remain the gold standard here; Korr may add big integers later.

4. Types, conversion and equality

Expression Node.js PHP 8 Python Korr
"1" + 1 "11" 2 TypeError TypeError (with a tip)
"5" * "2" 10 10 TypeError TypeError
0 == "" true false False false
[1, 2] == [1, 2] false (reference) true True true
int("42") parseInt("42") (int) "42" int("42") int("42")
int("abc") NaN 0 ValueError ValueError, or int("abc", 0) gives 0

Korr’s choice: Python’s strictness (no implicit conversion, structural ==), plus an explicit default for conversions that may fail (the most common real-world need when reading user input).

5. Arrays / lists

const xs = [3, 1, 2];
xs.push(4);
const sorted = [...xs].sort((a, b) => a - b);   // sort() mutates in JS
const doubled = xs.map(x => x * 2);
const last = xs[xs.length - 1];
<?php
$xs = [3, 1, 2];
$xs[] = 4;
$sorted = $xs; sort($sorted);                  // sort() mutates in PHP
$doubled = array_map(fn($x) => $x * 2, $xs);
$last = $xs[count($xs) - 1];
xs = [3, 1, 2]
xs.append(4)
sorted_xs = sorted(xs)
doubled = [x * 2 for x in xs]
last = xs[-1]
let xs = [3, 1, 2]
xs.push(4)
let sorted = xs.sort()                 // returns a new array
let doubled = xs.map(fn(x) => x * 2)   // or [x * 2 for x in xs]
let last = xs[-1]

Korr’s choice: JavaScript’s method style (xs.map(...), chainable), Python’s negative indexes, slices and comprehensions, and a clear rule: transforming methods return new arrays, only push/pop/insert/remove_at/clear/... mutate. Out-of-range access is an error (Python) instead of undefined (JS) or a warning (PHP); use xs.get(i, default) when a value may be missing.

6. Maps / objects / dicts

const user = { name: "Ana", age: 20 };
user.city = "Bandung";
const keys = Object.keys(user);
const city = user.address?.city ?? "unknown";
<?php
$user = ["name" => "Ana", "age" => 20];
$user["city"] = "Bandung";
$keys = array_keys($user);
$city = $user["address"]["city"] ?? "unknown";
user = {"name": "Ana", "age": 20}
user["city"] = "Bandung"
keys = list(user.keys())
city = (user.get("address") or {}).get("city", "unknown")
let user = { name: "Ana", age: 20 }
user.city = "Bandung"
let keys = user.keys()
let city = user.address?.city ?? "unknown"

Korr’s choice: JavaScript’s literal syntax and dot access, Python’s ordered dict semantics and methods, and ?. / ?? from JS/PHP: the shortest safe way to read nested, possibly-missing data such as JSON requests.

7. Destructuring and spread

  Node.js PHP Python Korr
array const [a, b, ...rest] = xs [$a, $b] = $xs a, b, *rest = xs let [a, b, ...rest] = xs
object/map const { name, age: years } = u ['name' => $name] = $u No let { name, age: years } = u
spread into array [...a, ...b] [...$a, ...$b] [*a, *b] [...a, ...b]
spread into map { ...a, x: 1 } [...$a, 'x' => 1] {**a, "x": 1} { ...a, x: 1 }
spread into call f(...args) f(...$args) f(*args) f(...args)

Korr’s choice: JavaScript’s syntax, which covers both arrays and maps consistently with a single ....

8. Conditions, ternary and null handling

if (score >= 90) { grade = "A"; } else if (score >= 75) { grade = "B"; } else { grade = "C"; }
const label = n > 1 ? "items" : "item";
const name = input ?? "guest";
<?php
if ($score >= 90) { $grade = "A"; } elseif ($score >= 75) { $grade = "B"; } else { $grade = "C"; }
$label = $n > 1 ? "items" : "item";
$name = $input ?? "guest";
if score >= 90: grade = "A"
elif score >= 75: grade = "B"
else: grade = "C"
label = "items" if n > 1 else "item"
name = input_value if input_value is not None else "guest"
// no-check
if score >= 90
    grade = "A"
else if score >= 75
    grade = "B"
else
    grade = "C"
let label = n > 1 ? "items" : "item"
let name = input_value ?? "guest"

Korr’s choice: Python’s indentation and readable and/or/not (no &&, ||, !), spelled-out else if (no elif/elseif to remember), and the familiar c ? a : b and ?? from JS/PHP.

9. Loops

  Node.js PHP Python Korr
count for (let i = 0; i < 5; i++) for ($i = 0; $i < 5; $i++) for i in range(5): for i in 0..5
inclusive i <= 5 $i <= 5 range(1, 6) for i in 1..=5
values for (const x of xs) foreach ($xs as $x) for x in xs: for x in xs
index + value xs.forEach((x, i) => ...) foreach ($xs as $i => $x) for i, x in enumerate(xs): for i, x in xs
map entries for (const [k, v] of Object.entries(m)) foreach ($m as $k => $v) for k, v in m.items(): for k, v in m
while while (c) {} while ($c) {} while c: while c
break / continue Yes Yes Yes Yes

Korr’s choice: Rust’s ranges (0..5, 1..=5: the end is visible in the code) and PHP’s foreach ($m as $k => $v) convenience as for k, v in m. There is no C-style for(;;), which is the source of most off-by-one errors.

10. Pattern matching

// Node.js has no pattern matching; switch compares with ===
switch (true) {
  case code === 200: msg = "ok"; break;
  case code >= 500: msg = "server error"; break;
  default: msg = "other";
}
<?php
$msg = match (true) {
    $code === 200 => "ok",
    $code >= 500 => "server error",
    default => "other",
};
match code:
    case 200: msg = "ok"
    case c if c >= 500: msg = "server error"
    case _: msg = "other"
// no-check
let msg = match code
    200 => "ok"
    500..=599 => "server error"
    [first, ...rest] => "a list"
    _ => "other"

Korr’s choice: a match expression (PHP 8, Rust) with Python’s binding and guards, Rust’s range patterns and alternatives (1 | 2), and an error when nothing matches (like PHP’s UnhandledMatchError) so missing cases are never silently ignored.

11. Functions

function greet(name, greeting = "Hello", ...rest) { return `${greeting}, ${name}`; }
greet("Ana");                         // no named arguments in JS
const double = x => x * 2;
<?php
function greet(string $name, string $greeting = "Hello", ...$rest): string {
    return "$greeting, $name";
}
greet(greeting: "Hi", name: "Ana");
$double = fn($x) => $x * 2;
def greet(name: str, greeting: str = "Hello", *rest) -> str:
    return f"{greeting}, {name}"
greet(greeting="Hi", name="Ana")
double = lambda x: x * 2
fn greet(name: str, greeting = "Hello", ...rest) -> str
    return "{greeting}, {name}"
print(greet(greeting: "Hi", name: "Ana"))
let double = fn(x) => x * 2

Korr’s choice: PHP 8’s named arguments with name: value and its enforced type declarations; JavaScript’s ...rest and arrow bodies (=> expr); multi-line lambdas (missing in Python); and hoisting, so helpers can live below the code that uses them.

12. Classes vs structs

class User {
  constructor(name, age = 0) { this.name = name; this.age = age; }
  greet() { return `Hi ${this.name}`; }
  static guest() { return new User("guest"); }
}
<?php
class User {
    public function __construct(public string $name, public int $age = 0) {}
    public function greet(): string { return "Hi {$this->name}"; }
    public static function guest(): self { return new self("guest"); }
}
from dataclasses import dataclass
@dataclass
class User:
    name: str
    age: int = 0
    def greet(self): return f"Hi {self.name}"
    @staticmethod
    def guest(): return User("guest")
struct User
    name: str
    age: int = 0

impl User
    fn greet(self) => "Hi {self.name}"
    fn guest() => User("guest")

let u = User("Ana", age: 20)

Korr’s choice: Rust’s separation of data (struct) and behaviour (impl), with Python dataclass conveniences (typed fields, defaults, readable printing, structural equality) and PHP-style runtime type checks on every field. No new, no this, no constructor boilerplate. Inheritance is intentionally left out for now; composition and traits (planned) cover the same needs more simply.

13. Errors

try { risky(); } catch (err) { console.log(err.message); } finally { cleanup(); }
throw new Error("boom");
<?php
try { risky(); } catch (Exception $e) { echo $e->getMessage(); } finally { cleanup(); }
throw new Exception("boom");
try:
    risky()
except Exception as err:
    print(err)
finally:
    cleanup()
raise Exception("boom")
// no-check
try
    risky()
catch err
    print(err.kind, err.message, err.line)
finally
    cleanup()
throw error("boom", "MyError")

Korr’s choice: the shared try/catch/finally model, with errors that are simple values carrying a kind (match on it instead of building class hierarchies), the line number, a call trace, and a fix-it hint for built-in errors.

14. Modules

  Node.js PHP Python Korr
import import { add } from "./math.js" require "math.php"; from math_utils import add import "./math.krr" as math
export export function add everything global everything everything not starting with _
run only when main require.main === module (CommonJS) No if __name__ == "__main__": if os.is_main()
file’s directory import.meta.dirname __DIR__ Path(__file__).parent __dir__

Korr’s choice: explicit relative paths (no search-path surprises), one namespace per module, Python’s _private convention and a readable os.is_main().

15. Type hints

  Node.js PHP Python Korr
syntax (TypeScript) x: number int $x x: int x: int
nullable x?: number ?int $x Optional[int] / int \| None ?int
enforced at runtime No Yes No Yes

Korr’s choice: Python’s name: type syntax with PHP’s runtime enforcement. Annotations are optional, so scripts stay short and larger apps get safety where it matters.

16. JSON, files, environment

Task Node.js PHP Python Korr
encode JSON JSON.stringify(v) json_encode($v) json.dumps(v) json.encode(v)
decode JSON JSON.parse(s) json_decode($s, true) json.loads(s) json.decode(s)
read a file fs.readFileSync(p, "utf8") file_get_contents($p) open(p).read() fs.read(p)
write a file fs.writeFileSync(p, s) file_put_contents($p, $s) open(p, "w").write(s) fs.write(p, s)
CLI arguments process.argv.slice(2) array_slice($argv, 1) sys.argv[1:] os.args()
environment process.env.PORT ?? "80" getenv("PORT") ?: "80" os.environ.get("PORT", "80") os.env("PORT", "80")
exit code process.exit(1) exit(1) sys.exit(1) os.exit(1)
run a program execFileSync("git", ["log"]) exec("git log") (shell) subprocess.run(["git", "log"]) os.exec("git", ["log"])

Korr’s choice: short, predictable module functions (fs.read, json.encode) with no imports, and process execution that never invokes a shell.

17. Web: server, routing, templates

// Node.js + Express (npm install express)
const express = require("express");
const app = express();
app.get("/users/:id", (req, res) => res.json({ id: req.params.id }));
app.listen(8080);
<?php
// PHP: one file per route behind Apache/Nginx, or a framework (Laravel/Slim)
header("Content-Type: application/json");
echo json_encode(["id" => $_GET["id"] ?? null]);
# Python + Flask (pip install flask)
from flask import Flask
app = Flask(__name__)
@app.get("/users/<id>")
def user(id): return {"id": id}
app.run(port=8080)
let app = http.app()
app.get("/users/:id", fn(req) => { id: req.params.id })
app.listen(8080)

Escaping user input in HTML:

Node.js PHP Python Korr
manual or a template engine htmlspecialchars($name) every time Jinja2 with autoescape automatic in html"<p>{name}</p>"

Korr’s choice: Express-style routing (:id parameters) and Flask’s “return a dict to get JSON”, built into the language with secure defaults (escaping, headers, limits, safe static files). This is PHP’s original promise (write a page and serve it) without PHP’s footguns.

18. Passwords and security helpers

Task Node.js PHP Python Korr
hash a password crypto.scrypt(pw, salt, 64, cb) + store salt yourself password_hash($pw, PASSWORD_DEFAULT) hashlib.pbkdf2_hmac(...) + store salt yourself crypto.hash_password(pw)
verify manual compare password_verify($pw, $hash) manual compare crypto.verify_password(pw, hash)
random token crypto.randomBytes(32).toString("hex") bin2hex(random_bytes(32)) secrets.token_hex(32) crypto.token()
constant-time compare crypto.timingSafeEqual hash_equals hmac.compare_digest crypto.equal

Korr’s choice: PHP’s excellent hash/verify pair API: the salt and parameters are stored inside the hash string, so there is nothing to get wrong.

19. Testing and shipping

  Node.js PHP Python Korr
test runner node --test PHPUnit (Composer) python -m unittest / pytest korr test
assertion assert.strictEqual(a, b) $this->assertSame($b, $a) self.assertEqual(a, b) / assert assert_eq(a, b)
simulate HTTP request in tests supertest (npm) framework tools Flask test client app.request("GET", "/")
one-file executable SEA: config + postject No PyInstaller korr build app.krr

What Korr adds

Features that none, or only one, of Node.js, PHP and Python provide out of the box:

  1. Compile-time name checking: typos and undeclared variables are reported before any line runs, with “did you mean” suggestions.
  2. Auto-escaping html"..." templates that compose without double escaping.
  3. A built-in web router with secure headers, request limits, timeouts and traversal-proof static files, no framework.
  4. app.request(): test any route without opening a port.
  5. korr build: any script becomes one self-contained executable, with cross-platform bundling via --runtime.
  6. Checked integer overflow: never wraps, never silently becomes a float.
  7. Default values for conversions: int(text, 0) instead of try/catch.
  8. Range patterns, guards and array patterns in match, as an expression.
  9. Errors with hints and call traces, printed with the source line.
  10. Shell-free process execution only: command injection is not possible through os.exec.
  11. Fluent line continuation: lines starting with .method() or |> continue the expression, without backslashes or wrapping parentheses.
  12. Batteries included, one binary: web server, databases, HTTP client, regex and logging ship inside one ~8 MB executable; there is no node_modules, vendor or virtualenv to audit (and --no-default-features builds a zero-dependency Korr).

Not in Korr yet

Being honest about gaps helps you choose the right tool. The roadmap shows what is planned and in which order:

Missing Workaround today
async/await, concurrent HTTP serving run several instances behind a reverse proxy
Generators / yield return arrays, or use callbacks
Connection pools, TLS to the database, SQL Server / Oracle one connection per app; PostgreSQL/MySQL over a trusted network or Unix socket
Central package registry Git-based packages: korr add github:user/repo@v1
HTTPS in the built-in server terminate TLS in a reverse proxy (the HTTP client supports HTTPS)
Inheritance, interfaces / traits composition (a struct field holding another struct)
Sets maps with true values, array.unique()
Big integers / decimals floats, or integer cents for money
Named time zones with daylight saving (IANA, e.g. Europe/Berlin) fixed UTC offsets: time.format(fmt, ms, 420)
Threads in programs server workers for web apps; separate processes with os.exec otherwise
Streaming file downloads send files from app.static or a reverse proxy

Performance

Korr compiles your program to bytecode for a register-based virtual machine (src/compiler/, src/runtime/vm.rs), written in safe Rust: every register and array access is bounds-checked and there is no unsafe code in the VM. The compiler resolves every variable at compile time (to a register, a global slot or a captured cell) and emits specialised instructions for common patterns (x += i, n < 2, for i in a..b, direct calls to known functions). Plain integer and float arithmetic, comparisons, jumps, loops, array/map indexing and field reads run in a tight inner loop that never touches the rest of the interpreter.

The numbers below are from one laptop (Intel Core 7 240H, Linux, Korr 0.13.1, PHP 8.4 without extensions, Node.js 24, Python 3.12); your numbers will differ. They come from python3 bench/run.py, which runs 23 workloads in six categories in all four languages. Every case computes a checksum that must be the same in every language, runs in its own process, is warmed up once and then timed (start-up excluded), and takes at least about 10 ms so that timer noise does not matter; the table shows the median of 5 runs. The full report, with every case, peak memory and the checksums, is in bench/RESULTS.md.

Summary: geometric mean of language time / Korr time per category. Above 1.00x means Korr is faster, below 1.00x means Korr is slower.

Category Cases PHP 8.4 Node.js 24 Python 3.12
Core language (loops, floats, calls, closures) 4 0.60x 0.08x 1.87x
Collections (arrays, sorting, maps, callbacks) 6 0.72x 1.37x 1.71x
Strings 4 0.75x 1.21x 1.22x
Structs and objects 2 0.59x 0.05x 1.41x
Classic algorithms (n-body, binary trees, sieve, spectral norm) 4 0.45x 0.07x 1.03x
Standard library (JSON, regex, SHA-256) 3 0.52x 0.99x 1.86x
All 23 cases 23 0.61x 0.35x 1.49x

Korr 0.10 scored 0.41x, 0.22x and 0.85x on the same suite; see the changelog for what changed since.

A selection of cases, in ms (lower is better):

Case Korr PHP Node.js Python
loop_int: sum of 0 .. 10 M 41 40 5.3 245
fib_recursive: fib(27) 23 7.2 1.5 15
array_index: index 1 M elements 14 12 31 48
array_sort: sort 200 K integers 22 36 60 57
map_string_keys: 200 K writes + reads 43 20 63 61
concat: s += "x" 1 M times 19 11 8.5 26
struct_method: 300 K structs + method calls 47 22 2.6 57
nbody: 50 K steps 150 77 3.3 153
json: encode + decode 20 K records 15 13 13 28
regex: find 13 K e-mails in 1 MB, 10 times 10 9.0 42 115
sha256: 20 hashes of 1 MB 69 13 18 21
Start-up (print one line, whole process) 4.6 30 33 28
Peak memory, geometric mean over all cases (MiB) 26 23 66 23

What this means today:


Previous: Extending Korr with Rust Docs index