Latest Publications

Chapter 2, Pong

It’s not perfect, but here is pong on the canvas!


Your browser does not support HTML5 Canvas.

Share

Speed of Singletons

One of the most popular Javascript patterns is the Singleton. It’s extremely useful way to create namespaces and organize your code.

The thing I’ve been wondering, what is the performance cost when using namespaces? I created a loop that sets a variable 1,000,000 times and records the result.

Let’s test it!

Singleton/Namespace Speeds

Results:

In this chart, I test the three browsers I use (on OSX), Firefox, Safari, and Chrome. The X axis shows how nested the namespaces were during the test. Literal was just the number 5, and Scope is a single variable in the function scope. Unsurprisingly Safari and Chrome are almost identical.The surprising part is how slow firefox was during the tests. Without running the test on more browsers, it leads me to think that there is something wrong with my testing method. I thought maybe that Safari and Chrome realized that the value didn’t change in each loop, so I modified the test to add i each time. Still the speed returned the same result. I’d be surprised if the next version of firefox didn’t bring this up to speed with the other two browsers.

Conclusion:

Should you worry about the speed when using Singletons as namespaces? Not at all. It took looping 1,000,000 times to get results that I could display. Unless you are processing that many items, I wouldn’t worry about the speed. Keep using namespaces and keep the global clean.

The Test Code:

            //Lets run some speed tests
            var total_runs = 1000000;
            var FIVE = 5;

            var i = total_runs;
            var tmp;
            var start = +new Date();
            while(i--) {
               tmp = 5;
            }
            var end = +new Date();

            $("#d").append("Literal " + (end - start));

            i = total_runs;
            start = +new Date();
            while(i--) {
                tmp = FIVE + i;
            }
            end = +new Date();

            $("#d").append("Scope " + (end - start));

            i = total_runs;
            start = +new Date();
            while(i--) {
                tmp = NS.FIVE + i;
            }
            end = +new Date();

            $("#d").append("NS.FIVE " + (end - start));

            i = total_runs;
            start = +new Date();
            while(i--) {
                tmp = NS.BOO.FIVE + i;
            }
            end = +new Date();

            $("#d").append("NS.BOO.FIVE " + (end - start));

            i = total_runs;
            start = +new Date();
            while(i--) {
                tmp = NS.BOO.BAR.FIVE + i;
            }
            end = +new Date();

            $("#d").append("NS.BOO.BAR.FIVE " + (end - start));

            i = total_runs;
            start = +new Date();
            while(i--) {
                tmp = NS.BOO.BAR.CAR.FIVE + i;
            }
            end = +new Date();

            $("#d").append("NS.BOO.BAR.CAR.FIVE " + (end - start));
Share

59. Silent Partner

“That’s a … nice … dress you got on there captain.” A midget stared up at me though an eye patch and a thick clump of hair over his eyes.

“Oh no I’m not–” I tried to say. I held a small basket of fish and herbs close to my chest. A man has never approached me outside of school before.

“The ship is ready to launch.” He tuned and took several steps down the pier.

I stood and watched as this little hairball of a man swung his legs back and forth in an effort to walk. It took him several of these exaggerated steps just to achieve a normal gait. I’d seen men in the village walk like that before. He was bow-legged. I thought it was from ridding horses, how would a sailor get it?

The midget stopped and turned, like a toy top trying to keep centrifugal force from pulling itself apart, to face me. “You were right captain, the island can only be found as the sun sets.” He took a few more steps before turning around to face me again. “If we leave now we’ll make it in time.”

“But I’m not…” captain, me? I followed him on to a rather large ship. The sheer size of it made him look more like a barnacle than a crew member. We walked past giant egg shaped men covered in fur. They had huge round bellies and short stubby arms and legs. I had to hold back laughter because they wobbled when they walked.

We climbed a set of stairs and the midget took stage on a small platform above the deck, overlooking the entire crew. I quickly brushed hair over my face as the midget spoke.

“We are about to set off for the island! Soon we will be rolling in treasures beyond our wildest dreams.” He looked at me. “Why don’t you say a few words before we set sail?”

I took the stage as he created a psychological vacuum with the large sweeping motions of his legs. I took a deep breath and lowered my voice. “I’m sorry… I um–”

“Don’t be sorry captain, I can’t even dress myself.” One sailor laughed, holding up stump arm. “We could kill the tailor if you like.” They all howled with laughter now.

I looked down my dress. It was a pretty blueberry color with a floral pattern. It was the best dress I owned. I held out the dress with my hand and twirled in the breeze. I was beautiful.

The midget, running as fast as his bent legs would allow, crossed in front of me to yell at the men. “You ugly scum wouldn’t know fashion if it hit you in the face.” He apologized to me. “I’m sorry captain; it’s a very lovely dress, not your normal silk or gold, but still very beautiful, in a commoner sort of way.”

The men howled in laughter.

“Alright you lazy bastards, set sail.” The midget waved his hand at the men like he was the giant and they were the flies. He walked down the stairs and I followed him into a large room in the back of the ship.

Lights and colors danced over my eyes as I looked around the room. Racks of neatly organized dresses, shirts, hats, and shoes covered the walls. Each was carefully color-coded creating a rainbow as one set flowed into the next. The display drew my eyes to the back of the room. Velvet curtains glowed in the sunlight behind a large wooden desk.

The midget stood in front of the desk, his head barely over the top. I walked around and sat in a plush leather chair. It was like sitting on a cloud, as I sank it formed around me, supporting every inch of my body.

“Alright captain, now we just need the final location.” He pulled out a large rolled piece of paper from his jacket. The paper was almost as long as his entire body. Was that why he walked funny? He had trouble unrolling the paper. He put a push pin in one corner, sticking it to the desk, and walked around the desk sticking pins in the other corners until it laid flat. It was a map.

“We just came from the Bering Strait and I’m pretty sure it can’t be any farther east because the water is just too shallow for an island.”

He pointed at one mass of squiggly lines after another on the map. I’d never even seen a map before. I couldn’t tell which parts were water and which where land.

“So you learned the final location?” he asked me.

I just smiled. I could feel the blood trying to rush to my face. It took every ounce of strength just to keep it down.

“So it is in the Dead Waters after all. Any ship would be crazy to sail in there.” He laughed so I laughed too. “Good thing we’re not any ship!” He pulled the map off the desk, ripping the pins out. “I’ll inform the navigator.” He wobbled back and forth as he made the long walk to the door. With his hand on the knob he turned and smiled at me. “I don’t know how you do it, but you always pull though for us.” With that the midget left.

I got up from the desk and walked over to a row of shoes covered in rubies. “And who said men don’t listen.”

©Chris Richards 2009
Share

Node.js

Recently I’ve fallen in love with node.js a web server written in JavaScript.

Ok it’s not really a web server, it makes IO functions available to JavaScript code in a completely non-blocking way! What does that mean? It means it’s incredibly fast. Yeah ok, how fast is incredibly fast I hear you saying. Right now in testing people are getting a node.js server that can handle 15,000 simultaneous comet requests. With some effort they think they can push that up to 100,000 simultaneous comet requests! The fastest web server that I know of is nginx which (according to WordPress) can handle 8,000 connections a second.

But it’s JavaScript you say, JavaScript isn’t fast. It must be witchcraft!

Kind of, node.js is using Google’s v8 engine, which is the fastest JavaScript available. (Some guys even made an NES emulator.) The other step is to get away from the threading system that most web servers use. It’s inefficient and wastes a lot of resources. If you want to know more, read up on the node.js website.

What do I plan on doing with node.js? Well so far I created an auto loader for help with developing. I’m also going to try my hand at a simple MVC framework for node.js. I’ve also been thinking about a Facebook game running off of node.js or something to watch and track changes on files at work. There are a lot of possibilities, most of which I haven’t even begun to scratch the surface. If you like JavaScript, I suggest you give node.js a try.

Share

Star Rating Plugin for jQuery

What

An easy to use rating control. It takes a normal select box, and turns it into a rating that your users can click on. The select box is preserved so you can still bind on change, get, and set the value in the rating control. The image is controlled with CSS and a simple gif, so you can make it look like anything you need.

(more…)

Share

Javascript, jQuery, Scope, and this

I want to talk a little bit about scope. Normally, scope is an easy concept, but there are a few little twists and turns in Javascript that make scope more complicated than it would seam. First, some basics.
(more…)

Share

jQuery serializeForm

What:

A plugin for jQuery that makes serializing input elements easy. Once serialized you can send the elements back to the server with AJAX.

Why:

There is a big problem with jQuery’s built in $.serialize() method. It only uses the input elements name attribute. In practice I found that the name attribute is rarely used, most people use the id attribute instead. The only exception is the radio input, then you have to use the name attribute. This plugin will attempt to use the id attribute first, if it’s blank, it’ll use the name attribute instead.
(more…)

Share

96. One Moment

Cooked ground beef and spices filled the air. Chris’ mouth watered. “Three hard tacos” Chris said, his voice louder than normal. Sounds of people eating and talking filtered though an open doorway. He rubbed the stiff dollars between his thumb and fingers while the cashier silently punched the keys. Even with beef in the air, he could still smell the fresh ink on the bills. The cashier took the money in exchange for a smooth slip of paper.

“Our Janet is now the Magenta, and Brad is now Frank-N-Furter. We have just about every one. We just need to fill those two parts.” Hanna forced an empty cup into the soda fountain. The whoosh of Coke emitted carbonation in the air.

Chris’s nose twitched, the dry carbon smell of fresh Coke blocked out the dark spice smell from Hanna’s lotion. “I think I know someone for Brad, but we still need a Janet. The girls have a problem with undressing on stage.” Chris talked into the filling cup. The moment the carbonation reached the top, he brought it up.  He bit at the foam, inhaling the carbonation, canceling even the strong smell of beef.

“Janet” a brave feminine voice said. “Brad Majors and Janet Weiss?”

Chris and Hanna turned to see a petite girl behind them. She too was clutching a thin, impossibly smooth slip of paper. Their eyes darted along this girl. Her All-Star shoes, torn jeans, and band tee competed with Hanna’s fish net gloves, tight pants, and knee high boots.

“Yeah.” Hanna didn’t take her eyes off the girl. “We’re putting on the Rocky Horror Picture Show.”

Chris quickly wiped the foam away from his nose. Vivid red and green flowers encircled on her shoes.

“I Love Rocky Horror” she squealed. “Do you have any parts left? Can I audition? I used to MC for it back in my home town. I did it every year.” Her body bounced as one leg bent slightly back and forth.

“Do you mind running around in your underwear in front of 300 people?” Hanna asked.

Chris concentrated hard to hear the cashier call his order number.

“Not at all, I’m Kassi.” She held out her hand.

Hanna shook it. “I’m Hana the producer, and this is Chris the director. Just come to rehearsal tomorrow at 7.”

“I’ll be there.” Kassi turned around to wait for her food.

Chris and Hanna found an empty table. “Do you think she’ll show up?” Hanna asked.

“I hope so.” Traces of an unknown shampoo lingered in the air.

©Chris Richards
Share

47. Smart Pets

A soon as my girl walks in the door I rub on her leg. Smells of the outside world sift though my nose. The place she spends her days, the one filled with strawberries, cigarettes, and chicken. I love smelling my girl on these days. She bends over so I can lick the chicken stains off her fingers. Her breath is slow and steady; it was a good day for her. I decide to test my luck and pull her into the kitchen. I was right, she grabs some treats from the cupboard.

After feeding me a few, she moves though the kitchen, her heart starting to pump faster. I jump to the counter and draw her attention. She’s gathering items together, she must be cooking. She waves me off the counter and I find a nice warm spot along the wall. I sit and watch her as she cooks. The metal pans clank together with a dull, old sound. Spices start to fill the air and steam covers her face. She’s starting to sweat, that means she’ll cover herself in fake pine and cinnamon smells before my man comes home. I drift off to sleep; she’s not going anywhere for a while.

I awake to the sound of a distant, heavy door opening and the jingle of keys. It’s my man. I look around to find my girl; she’s not in the kitchen anymore. The smell of boiled meat and grain mixed with some sort of spice. I consider getting up, but the surrounding air is cold and my man won’t feed me treats. The front door opens and my man walks in with a large paper bag covering his face. His keys continued to jingle as he walks into the kitchen. He calls out to my girl. None of the sound indicated me so I stayed put.

My man scratched my head quickly as he searched the house for my girl. His hands smelled like wild flowers and a hint of something musky. They both came back from the bedroom. He walked out first, then she came up from behind him and pounced. She cleaned the side of his face and he carried her into the kitchen. I could smell her sex. She never presented for him. This whole process would be easier if she just presented and called for him. They will spend the whole evening in a cat and mouse game. Some nights they spend so long playing this game that they never get around to mating. I find my way to the couch and go back to sleep.

The noise box woke me up again. They are both sitting on separate sides of the couch. She still had a lingering aroused smell, but no mating smell. Another failed attempt tonight. I hopped down on her lap to comfort her. Her fingers had a similar musky smell. I purred and she stroked my back. Her heart slowed and her breathing matched mine. The night’s not over, maybe she can try again.

&copyChris Richards 2009
Share

13. God

Humanity doesn’t need faith in me, they need hope in themselves. For example let’s look at these two teenagers, Bruce and Sofie. Every Monday and Wednesday, they sit next to each other in history class. I watch as Sofie spends the class writing “Bruce” over and over in her notebook. She dreams about him talking to her, asking her out. Anxiety and hormones slush in her brain, creating an intense battlefield, leaving her paralyzed. Bruce fights the same battle as he tries to not stare at Sofie’s snug breasts each day. As I look into their futures, I see that their anxieties will prevent them from realizing their mutual attraction. Even if I put them in a group project together, force them to talk, they would still be too paralyzed to act upon these desires.

And yet, despite these anxieties, they continue to fantasize about each other. They cannot see their own future, so they live on, in hope that one day, things will work out. Bruce could overcome this anxiety with a little self esteem, but he doesn’t know how to build it. His culture has lost this knowledge and replaced it with something they call “will power.” He doesn’t take control of his own life; he’s too scared, so he becomes a blade of grass, just accepting whatever comes his way. Sofie spends the semester praying. Instead of talking to me, she should be talking to Bruce. This passive acceptance creates a downward spiral causing the anxiety and depression to build. These forces can take over their minds, until one day they break. And yet, I can see their future, and I know they never break. Because they hope for the future, they believe things can change, even when they’re too scared to act on them. It’s hope that ultimately drives humanity, and I’m alright with that.

© Chris Richards 2009

Share