JS++ 0.5.2: BSD License, Interfaces, Abstract Classes, Virtual Methods, Non-generic Standard Library Classes

You’ve asked and we’ve listened. JS++ is now licensed under the 3-clause BSD License.

When we first announced 0.5.1 back in March, we introduced bare minimum classes. Specifically, I noted the following class features were unavailable:

  • Generic classes
  • Abstract classes
  • Inner classes
  • Interfaces
  • Virtual methods
  • Custom Conversion Rules as defined in my book, “The JS++ Type System”, Chapter 6.2

Every feature in the above list that isn’t crossed out is now available except the last feature (custom conversion rules) which will be arriving next. In addition, today’s release marks the introduction of the Standard Library. I’m going to briefly introduce the new features.

Update to Hello World

The JS++ Hello World program is now written as:

import System;

Console.log("Hello World");

Notice we no longer have to declare console as external. external is used for importing JavaScript libraries, and since we didn’t have a JS++ console implementation yet, we resorted to using the JavaScript console. However, now that we have a Console class in the Standard Library, it’s no longer a problem.

It is always recommended that you use the Standard Library’s Console class over the external JavaScript console. JS++ will detect if a console is available and will not crash if you try to log to an unavailable console. This can be a problem for web browsers like older versions of Internet Explorer, which are still used heavily in enterprise web applications.

Standard Library

The following Standard Library classes are now available:

  • System.Boolean
  • System.Character
  • System.Console
  • System.Date
  • System.Double
  • System.Exception
  • System.Exceptions
  • System.Integer8
  • System.UInteger8
  • System.Integer16
  • System.UInteger16
  • System.Integer32
  • System.UInteger32
  • System.Math
  • System.Object
  • System.RegExp
  • System.String

Many of the above classes, such as System.String and System.Integer32, are wrapper classes for auto-boxing. Currently, these wrapper classes simply provide a type-safe (and sometimes optimized) version of their JavaScript-equivalent methods. For example:

import System;

string s = "my string";
Console.log(s.replace(/^[a-z]/, string(string match){ return match.toUpperCase(); })); // Prints "My string"

The above example provides the exact same functionality as JavaScript’s String.prototype.replace. However, you get safety guarantees that you wouldn’t get with JavaScript. For example, if you try to call System.String.replace using the wrong arguments:

Console.log(s.replace(1));
[  ERROR  ] JSPPE5023: No overload for `System.String.replace' that takes `1' argument(s) at line 4 char 12 at replace.jspp

Optimizations

Always favor using the JS++ Standard Library over “rolling your own” functions. Consider the following code (which you can run yourself with the latest JS++):

import System;

double t = (new Date).getTime();
string z;
for (int i = 0; i < 5000000; ++i) {
	z += Double.POSITIVE_INFINITY.toString();
}
Console.log((new Date).getTime() - t);

And the nearly equivalent JavaScript code:

var t = (new Date).getTime();
var z = "";
for (var i = 0; i < 5000000; ++i) {
	z += Number.POSITIVE_INFINITY.toString();
}
console.log((new Date).getTime() - t);

JS++ average time: 124.4ms
JavaScript average time: 211ms

In this case, JS++ is roughly 70% faster... for nearly identical code.

You may think JS++ adds overhead (based on perceptions of what fast code may look like), but well-written JS++ will be faster than JavaScript. See my other article on optimization for more details.

Typed Exceptions and Multiple Catch Clauses

JS++ 0.5.2 introduces the System.Exception class and enables you to create your own custom exceptions.

Here's an example:

import System;

class CustomException : System.Exception
{
    CustomException() {
        super();
    }
    CustomException(string message) {
        super(message);
    }
}

try {
    throw new CustomException("This is a custom exception object.");
}
catch(CustomException e) {
    Console.log("Caught CustomException");
}
catch(System.Exception e) {
    Console.log("Caught System.Exception");
}

Variadic Parameters

The latest version of JS++ also introduces variadic parameters, which allow you to supply an arbitrary number of arguments to a function:

import System;

void log(Date date, ...string messages, bool silent) {
    if (silent) return;

    foreach(string message in messages) {
        Console.log(date.toString() + ": " + message);
    }
}

log(new Date(), "1", "2", "3", false);

Interfaces

An interface creates a contract. Methods defined in an interface must be implemented by all inheriting classes. Classes can inherit more than one interface.

According to JS++ naming conventions, interfaces should be prefixed with "I" and should be UpperCamelCase.

import System;

interface IWalkable {
	void walk();
}
interface ITalkable {
	void talk();
}

class Person : IWalkable, ITalkable
{
	void talk() {
		Console.log("Talking...");
	}
	void walk() {
		Console.log("Walking...");
	}
}

Person person = new Person();
person.talk();
person.walk();

Callback Type Parameter Names

Callback types can have parameters. Previously, you could only specify the parameter types for a callback/function type. However, you can now add names for these parameters. While these names cannot be used and have no meaningful effect on the executed code, they improve the readability of the code.

import System;

class Bird
{
	void fly() {
		Console.log("Flying...");
	}
}

void(Bird bird) fly = void(Bird bird) {
	bird.fly();
};
Bird bird = new Bird();
fly(bird);

Removal of 'Convert' Module

We have removed from the Convert module from the latest release. It was always used as a stopgap until we implemented the Standard Library wrapper classes, which provide toString() and other methods.

Bug fix: 'typeof' for internal types

For non-external types, typeof will always return the string "internal".

import System;

int x;
Console.log(typeof x); // "internal"

Virtual Methods

JS++ 0.5.2 introduces the virtual keyword and the override keyword to enable virtual methods on classes.

Virtual methods enable late binding and runtime polymorphism.

class Shape
{
    public virtual double area() {
        return 0;
    }
}
 
class Rectangle : Shape
{
    private int length, width;
 
    public Rectangle(int length, int width) {
        this.length = length;
        this.width = width;
    }
 
    public override double area() {
        return length * width;
    }
}
 
class Triangle : Shape
{
    private int base, height;
 
    public Triangle(int base, int height) {
        this.base = base;
        this.height = height;
    }
 
    public override double area() {
        return (base * height) / 2;
    }
}

Abstract Classes

Use the abstract modifier to create abstract classes and methods.

abstract class Shape
{
    public abstract int area();
}
class Rectangle : Shape
{
    private int length, width;
 
    public override int area() {
        return length * width;
    }
}

Enumerations

Enumerations (enums) can be used to restrict values and write type-safe code:

enum Importance { None, Regular, Critical }
 
Importance errorLevel = Importance.Critical;

The one missing feature...

Sadly, there is still one major missing feature from JS++. The Standard Library does not support System.Array yet because it is a generic class, and generics have not yet been implemented. In the meantime, you can resort to declaring your arrays as var:

var arr = [ 1, 2, 3 ];

BSD License

Last, but not least, JS++ 0.5.2 is the first version of JS++ licensed under the 3-clause BSD License.

The download for JS++ 0.5.2 is available from our home page.

Enjoy JS++!

Code Written in JS++ Can be Significantly Faster than the Equivalent JavaScript

JS++ type guarantees don’t just mean more reliable applications. They can also mean faster applications.

People have expressed concern about the “conversion overhead” that comes with the JS++ type system. However, we’ll show you today that having code that varies in type (such as JavaScript code) can be substantially slower, and even if you lose 1ms in JS++ “conversion overhead”, you may gain 10ms, 100ms, or more from typed optimizations that you can only get with JS++.

Here are two side-by-side benchmarks:

JS++: test.jspp

import System;

double t = (new Date).getTime();
string z;
for (int i = 0; i < 5000000; ++i) {
	z += i.toString();
}
Console.log((new Date).getTime() - t);
$ time node test.jspp.js
484

real	0m0.537s
user	0m0.496s
sys	0m0.100s
$ time node test.jspp.js
487

real	0m0.536s
user	0m0.500s
sys	0m0.096s
$ time node test.jspp.js
488

real	0m0.536s
user	0m0.508s
sys	0m0.088s
$ time node test.jspp.js
486

real	0m0.534s
user	0m0.480s
sys	0m0.116s
$ time node test.jspp.js
484

real	0m0.533s
user	0m0.496s
sys	0m0.096s

JavaScript: test.js

var t = (new Date).getTime();
var z = "";
for (var i = 0; i < 5000000; ++i) {
    z += i.toString();
}
console.log((new Date).getTime() - t);
$ time node sample.js 
523

real	0m0.575s
user	0m0.572s
sys	0m0.076s
$ time node sample.js 
518

real	0m0.561s
user	0m0.556s
sys	0m0.072s
$ time node sample.js 
524

real	0m0.572s
user	0m0.544s
sys	0m0.092s
$ time node sample.js 
521

real	0m0.565s
user	0m0.560s
sys	0m0.076s
$ time node sample.js 
519

real	0m0.563s
user	0m0.540s
sys	0m0.088s

Specifications:
Core i7-4790k
Linux x64 (Debian)
32gb RAM
Node.js v.7.9.0 (Google V8)
JS++ v.0.5.2

Take a close look at the JS++ code and the JavaScript code. They are nearly identical except the JS++ code has types and an import statement.

In this particular case, JS++ is roughly 7.2% faster than JavaScript on a basic toString() benchmark. We do some special things under the hood here, but it should be clear that even with the perceived overhead of JS++ conversions and the much heavier overhead of auto-boxing, JS++ code is still noticeably faster. However, the topic of today's post is not about toString(). If we slightly change the JavaScript code:

var t = (new Date).getTime();
var z; // variable is no longer initialized to string
for (var i = 0; i < 5000000; ++i) {
	z += i.toString();
}
console.log((new Date).getTime() - t);
$ time node sample.js 
735

real	0m0.779s
user	0m0.804s
sys	0m0.072s
$ time node sample.js 
735

real	0m0.783s
user	0m0.784s
sys	0m0.092s
$ time node sample.js 
749

real	0m0.794s
user	0m0.824s
sys	0m0.088s
$ time node sample.js 
742

real	0m0.787s
user	0m0.788s
sys	0m0.092s
$ time node sample.js 
738

real	0m0.782s
user	0m0.808s
sys	0m0.064s

Suddenly, JS++ has jumped from being ~7% faster to being 52.2% faster.

First of all, without static typing, you lose correctness. The result of the above small change results in "undefined0123..." rather than "0123...". Therefore, while it may not be the best benchmark, it illustrates the point. Besides losing correctness, the drop in performance is substantial when types change. You often see JavaScript code written where the type constantly changes, and you can see the cost of this negligence compared to JS++.

The reason this happens is because V8 optimizes "optimistically". When you initialize your variable to a string, V8's JIT code generator will generate code optimized for strings. However, when the type changes, V8 has to "de-optimize", change the variable type, convert data, and more. These are expensive operations which highlight how performance can degrade. The example we showed today involved only one variable. Imagine the performance difference in an application with thousands of variables.

Finally, the JS++ type system is patent-pending. I've made my case clear about patents being only used for competition. Since most programmers immediately jump to conclusions, I will use this example: you can use a patented skateboard without getting in trouble with the law; however, you cannot make and sell a patented skateboard without getting in trouble with the law. If you're on the fence with JS++, don't expect to see our technologies in TypeScript, Flow, or any competing language any time soon. You're free to use them, and we encourage you to do so if your only criteria when selecting technologies are "open source" and "unpatented."

JS++ is free, closed-source software licensed under the BSD License, and the benchmarks above can be executed with the latest JS++ 0.5.2 release.