Post-Rice Haze

Devin Naquin
Recent Rice alum. Living and coding.

Mar 11

JavaScript Inheritance

JavaScript inheritance can be done dozens of different ways. One of the major plusses of the language is that it’s flexible enough to allow many possible paradigms. However, this also turns into a major language detractor, since everyone does it just a little differently. Here are a couple and some reasons I lean one way most of the time.

First, there’s a functional pattern. I actually like this a lot. Probably because I’ve written way too much Scheme in my time, but it’s elegant and, through functional scope, provides privacy otherwise lacking in JavaScript.

For example:

var make_rectangle = function(length, width) {

	// length, width in private scope

	var area = function() {

		return length * width;

	};

	return {

		area: area

	};

};

var make_square = function(length) {

	return make_rectangle(length, length);

};

var r = make_rectangle(1, 2);

var s = make_square(2);

r.area();

s.area();

This is sometimes called the Module pattern and sometimes uses constructors with the new keyword, but that all amounts to the same thing: a function that generates an object.

The functional pattern is great, and I like it for lots of things but it has significant drawbacks. Privacy is rarely really needed and blocks lots of fun extensions once the object is created (e.g. r.perimeter = function() { return 2*this.length + 2*this.width; };) The subtle drawback is the performance hit it entails, which I will come back to.

Then there’s a classical-styled inheritance pattern. Which has it’s drawbacks but has grown on me in recent months.

function Rectangle(length, width) {

	this.length = length;

	this.width = width;

};

Rectangle.prototype.area = function () {

	return this.length * this.width;

};



function Square(length) {

	/* could use parent constructor here, but requires some more work. */

	this.length = this.width = length;

};

Square.prototype = new Rectangle();



var r = new Rectangle(1, 2);

var s = new Square(2);

r.area();

s.area();

This is pretty straightforward and understandable for someone coming from the OO world of doing things. Rectangle constructs an object that has a length and a width. The next line adds a function to it’s prototype. Square constructs similarly. And sets it’s prototype to an instance of Rectangle (it’s actual data doesn’t matter; so here, length and width are undefined).

Now this approach has it’s drawbacks too. There’s no easy way to call a parent’s constructor. This can be buttered over with some convenience functions if necessary. And the new keyword has it’s problems: without the new, calls to Rectangle and Square have this bound to the global namespace which can cause all kinds of crazy problems. As Crockford says, “There is no compile warning, and there is no runtime warning.” This used to bother me, but I’ve learned to live with lint. A capitalized function must always get called with new, done and done. Besides, if you’re extra paranoid, there’s always:

function Rectangle(length, width) {

	if (!(this instanceof Rectangle)) {

		return new Rectangle(length, width);

	}

	

	this.length = length;

	this.width = width;	

}

But this also has it’s advantages. For example, not only can I now extend individual objects, but I can also add functionality to the prototype itself. For example:

r.perimeter = function () { return 2*this.length + 2*this.width; };

r.perimeter();

Or:

Rectangle.prototype.perimeter = function () { return 2*this.length + 2*this.width; };

r.perimeter();

s.perimeter();

Which otherwise, the privacy would block. The subtle advantage is that the classical actually performs much better than our first pattern. A quick profile shows:

>>> function exercise_functional() {

	for (var i=0; i<100000; i++) {

		make_rectangle(1, 2).area();

	}

};

>>> function exercise_classical() {

	for (var i=0; i<100000; i++) {

		(new Rectangle(1, 2)).area();

	}

};
function calls time average

make_rectangle 100000 418.666ms 0.004ms

Rectangle 100000 95.361ms 0.001ms

A pretty big difference and a huge factor for objects in tight loops.

The classical pattern is much faster, because it’s doing much less. It makes one area function assigned to Rectangle’s prototype and the language delegates all calls to it up to that instance with the correct data bound to this. The functional pattern is making a new area function for every object. And assigning it to it’s own property. Not only wasting a bunch of time, but also memory.

JavaScript is fun. It lets you do all this any way you choose. Which is a blessing and a curse. My choice tends to change fairly frequently.


Comments (View)
Feb 27

Shoes

Nelly’s “Air Force Ones” is a classic. I remember riding around in the car in high school surfing radio stations in the attempt to always have “Air Force Ones” playing. It was ridiculous how long we could actually keep this up.

Since “My Adidas” was released by Run DMC in 1986, shoes have been a classic trope in hip hop, but nothing takes it to the extreme like “Air Force Ones”. And it’s the extremes that make “Air Force Ones” great. The complete necessity of something as trivial as a shoe. In multiples. “I said give me two pairs,/I need two pairs,/So I can get to stomping in my Air Force Ones.”

The song is just getting started when Murphy Lee comes in with a verse that’s only rhyme is the one word “man”.

Don’t get me wrong man, now Murphy Lee ain’t dumb man,
‘Cause if the shoe is on the shelf, you should have some man
You can not sit up and tell me that you have none man
You may not have three or four but you got one man.

I got into a long argument once in college when someone mentioned they hated 50 Cent because he rhymed lines with the same word. Murphy Lee’s verse is a solid example of why I rarely take offense to this. Just look at the endings “dumb man”, “some man”, “none man”, “one man”. Enough said.

Then Kyjuan comes in with a verse that mixes the shoes with the another hip-hop staple: the car. Another necessity that’s completely trivial.

O. K. ‘li, I treat my shoe like my ride,
Chrome on the fat laces and put wood on the inside
Spray candy on the swoosh with electric roof
Since I put a kit on the sole, now got a wider shoe
You see that low mid, skittle purple poof, I’m drivin them.
(Kyjuan, where you gettin’ them colors, are you dying them?)

Every time I hear this verse, I just picture it all literally. A tricked out high top complete with chrome, wood interior and candy paint. And I giggle. But they are both just accessories.

Finally, Nelly rounds it out with a verse about the white on whites. My favorites, though mine are scuffed.

Now don’t nothing get the hype on first site like white on whites
Them three quarters, them lows; they all tight
The only problem they only good for one night,
‘Cause once you scuff them you fucked up your whole night.

Look at that first line. The whole verse, like most of the song’s verses, is centered around a single rhyme. But here, it’s the first line that makes it all work. “Now don’t nothing get the hype on first site like white on whites”. It’s overloaded “hype”, “first site”, “like”, “white on whites”. A completely excessive line that matches the theme of the song.

I think I might need some new shoes.


Comments (View)
Nov 9

Dead Simple Concurrency with Clojure

Concurrency is hard. In an environment where processors don’t get faster, we just get more of them, concurrency is going to get more important. We’ll take these as givens.

Enter Clojure. Promising a vast array of interesting features promising to make concurrency easier.

So in my attempts to learn the language, my goal was to get something running concurrently as quickly as possible. I started with merge sort.

(use 'clojure.contrib.seq-utils)

; merge side of the merge sort. naive tail recursive solution.
(defn ms-merge [left right]
  (loop [head [] l left r right]
    (if (empty? l) (concat head r)
      (if (empty? r) (concat head l)
        (if (> (first l) (first r))
          (recur (conj head (first r)) l (rest r))
          (recur (conj head (first l)) (rest l) r))))))

; split side of the merge sort. naive recursive solution.
(defn naive-merge-sort [l]
  (if (< (count l) 2) l
    (apply ms-merge (map naive-merge-sort (split-at (/ (count l) 2) l)))))

This naive solution is slow and clearly doesn’t use both my cores.

Merge Sort Single Threaded

With a total running time of 21.98s to sort a shuffled list of 1M integers.

From here, I split the process between my cores.

; wrapper around merge sort that just delegates both sides
; to threads running the naive solution.
(defn parallel-merge-sort [l]
  (apply ms-merge (pmap naive-merge-sort (split-at (/ (count l) 2) l))))

The approach is just to split the input in half and sort both sides in different threads. This is trivial to do using pmap. The end job of merging these two together is easy enough and tail-recursive, so the downside of running the merge on just a single thread is less than you think (roughly 0.9% of total processing time).

Merge Sort Dual Threaded

And with a total running time of 16.25s to sort a shuffled list of 1M integers.

In this, I don’t use Clojure’s key win, STM, just the pmap syntactic sugar around managing multiple threads, so I’m only getting a little benefit from Clojure.

Also, this only splits the task into two parts, therefore only making use of at most two cores. Not a completely portable solution.

But the fact that my “hello world” in a new language uses both my cores this easily, is impressive.


Comments (View)
Sep 29

Really Liking Ruby

class Node

  def initialize(label, left, right)
    @label  = label
    @left   = left
    @right  = right
  end

  attr_accessor :label, :left, :right

  def breadth_first
unvisited = [self] while not unvisited.empty? node = unvisited.shift yield node unvisited << node.left if node.left unvisited << node.right if node.right end end end


Comments (View)
Aug 21

Migrated west until I hit an ocean. From the bayou to Houston to Austin. Skipped the desert and hit a beach. Cold as all hell up the foothills. I-10 always the closest thing to a home I had. Until I ran out of mile markers and there’s only east to go.


Comments (View)
Aug 13
“People. This is me again. I hate to cut things down like this. But, uh. There’s a crowd of kids. And this is to whom I’m talking. Mostly to whom. Are you ready for that? Um. There’s kids like crowding around over the walls, and like, trying to break down doors and everything. Thinking the Beatles are here. And uh. And uh that last comment. Hahaha alright. Except that they’re trying to break things down, crawling over ceilings and walls, and like. Thinking the Beatles are here. And they’re not. You. Those of you. And uh, they can come in if they want to come in. The Beatles aren’t here. Yeah. There’s great things happening anyway. Yeah, except that, just don’t, you know. Don’t like, bring down the ceilings and walls and everything. And uh, carry on.” Bill Graham at Monterrey Pop during the Grateful Dead’s set.

Comments (View)
Jul 23

Jurassic Park

MALCOLM
The problem with scientific power you’ve used is it didn’t require any discipline to attain it. You read what others had done and you took the next step. You didn’t earn the knowledge yourselves, so you didn’t take the responsibility for it. You stood on the shoulders of geniuses to accomplish something as fast as you could, and before you knew what you had, you patented it, packaged it, slapped it on a plastic lunch box, and now you want to sell it.

HAMMOND
You don’t give us our due credit. Our scientists have done things no one could ever do before.

MALCOLM
Your scientists were so preoccupied with whether or not they could that they didn’t stop to think if they should. Science can create pesticides, but it can’t tell us not to use them. Science can make a nuclear reactor, but it can’t tell us not to build it!


Comments (View)
Apr 20
“…that inside this building is the president, and not just any president—though admittedly that probably would not have mattered—but this is a president that, fuck, we have some sort of crush on this man. He speaks like a president, not always authoritative or anything but he can form sentences, complex sentences with beginnings and ends, subordinate clauses—you can hear his semicolons! He knows the answers to questions. He knows acronyms and the names of foreign leaders, their deputies. It is heartening, it makes our country look smart, and this is an important thing, something we have too long been without.” Dave Eggers about Clinton circa 1994 in A Heartbreaking work of Staggering Genius.

Comments (View)
Mar 29
“I need to see what’s inside that box. If I learned anything from 24, you’re going to want to zoom in and enhance.” 30 Rock, “Apollo, Apollo”

Comments (View)
Mar 16

A lot of people have used The Cure’s “Close to Me”, Diplo included. NME gives a rundown, but uses a terrible Diplo example.

Now Lady Sovereign’s thrown her two cents in with her new single. I like. Plus it’ll give me good material for Lady Sovereign/Diplo/The Cure extended transitions.


Comments (View)
Page 1 of 3