Strawman: Tuples

# Michał Wadas (11 years ago)

Should we have new type - tuples?

My proposal:

  • Tuples are immutable. Eg. var wow = new Tuple('my', 'little', 'Cthulhu'); wow[2] = 'Nyarlathotep'; // throws in strict mode, silently fails in sloppy mode
  • Tuples are primitive type. Comparison between tuples is based on identity of elements, not identity of tuples Eg: new Tuple(Object, Function, null, NaN) === new Tuple(Object, Function, null, NaN); // true
  • typeof new Tuple(); // 'tuple'
  • Tuple(['wow', 'a', 'b']) = new Tuple('wow', 'a', 'b'); // true
  • Tuple.prototype.add = function add() { return new Tuple(...this, ...arguments); }

Pros:

  • tuples are very memory efficient
  • comparision based on identity of elements is required in many cases Cons:
  • ???
# Jasper St. Pierre (11 years ago)

Why would tuples be any more memory efficient than objects or arrays?

# Jeremy Martin (11 years ago)

Michal - Why have it only throw in strict mode? Tuples would be a new construct, so no breaking of the web if it throws in all contexts.

Jasper - It's not necessarily a given, but the immutability of tuples offers some guarantees that are easier to optimize against. E.g., no need to pre-allocate extra space, as in most array implementations.

# Michał Wadas (11 years ago)

@Jasper: because tuples can be insanely optimized - their immutability (including fixed length) removes almost any overhead (JS objects overhead is quite big). Of course, modern engines can optimize array to be

@Jeremy: consistency with other immutable primitives and frozen objects. (function() { 'wow'[0]='a'; })() // undefined, silently fails (function() { 'use strict'; 'wow'[0]='a'; })(); //TypeError: 0 is read-only (function() { 'use strict'; Object.freeze({'oh': 'hai'})).oh = 'Cthulhu'; })(); // TypeError: "oh" is read-only (function() { Object.freeze({'oh': 'hai'})).oh = 'Cthulhu'; })(); // undefined, silently fails

# Salvador de la Puente González (11 years ago)

I'm not an expert but the JIT could keep all the lists as tuples until a modification is performed and then prevent further optimisation.

I don't know if current JITs are already doing this way.

# Brendan Eich (11 years ago)
# Salvador de la Puente González (11 years ago)

Did I say a nonsense about JIT and lists? Indeed, AFAIK, making:

var tuple = Object.freeze([1, 2]);

It is like having a tuple and the JIT could realize the object is frozen and perform the required optimizations.

# Brendan Eich (11 years ago)

Salvador de la Puente González wrote:

var tuple = Object.freeze([1, 2]);

Right, and #[1, 2] could transpile and give nice, compact syntax.

Too bad I put the comma operator in JS from day 1 -- Java did not but I followed C, the great grand-parent.

# Viktor Mukhachev (11 years ago)

Object.freeze do not solve the issue with WeakMap, right? ( strawman:value_objects )