Cost of try/catch in JavaScript

I know that in Java, using a try/catch is fairly expensive vs. a if check. Since JavaScript has the same syntax for the most part, I wrote up a simple benchmarking script to test it out. On my box, it outputs:

if avg: 0.029
try avg: 1.372

Note, that you'll need the Firebug plugin for Firefox in order to run this.

var tryFunc = function () {
  try {
    document.getElementById("fake").innerHTML = "hi there";
  } catch (e) {
    // eat it!

var ifFunc = function() {
  var el = document.getElementById("fake");
  if (el) {
    el.innerHTML = "hi there";

function benchmark(name, func) {
  var repeats = 1000;
  var elapsed = 0;
  var startTime =0;
  var endTime = 0;
  for (var i=0; i< repeats; i++) {
    startTime = new Date().getTime();;
    endTime = new Date().getTime();
    elapsed += (endTime - startTime);
  console.log(name + " avg: " + (elapsed / repeats ) );

benchmark( "if", ifFunc );
benchmark( "try", tryFunc );
Add a comment
Category: programming Tags:

HOWTO: Invoke a shell script on a file on save with emacs

At my current job, we use a lot of Template Toolkit. Due to some design decisions (that I consider a tad strange), we have to run a shell script on the template files (e.g. files that end with “.tt”) after they are saved in order for them to be displayed on the dev site.

Since I started using emacs about two months ago, I've learned quite a bit. A new thing on the learning heap is the after-save-hook. Emacs to the rescue yet again.

Here's a emacs lisp function I wrote to automate the execution of the script when a template file is saved:

(defun ssm-cheetah-after-save-hook ()
  "After saving a tt file, run the language_update file"
  (if buffer-file-name
        (setq is-tt-file (numberp (string-match "\.tt$" buffer-file-name)))
        (if is-tt-file
              (setq cmd (concat (getenv "B") "/bin/YOURSCRIPTHERE --template="))
              (shell-command (concat cmd buffer-file-name))
              (message "Updated template with %s" buffer-file-name))))))
(add-hook 'after-save-hook 'ssm-cheetah-after-save-hook)

What it does, is first defines a function that checks to see if we have a file name, (which should probably always be true since we are saving now that I look at it). If we do, check to see if the name ends with “.tt.” If it does, pass the name of the file to the shell script and output a message to the user saying the template was updated. Finally, the function is added to the after save hook.

Add a comment
Category: editor Tags:

Emacs Tips

Since I've been programming more Perl than Java lately, I've started using Emacs as my primary IDE. Been checking out a few sites with tips and tricks to help me along the path of conversion from vi to Emacs. Trey Jackson's blog seems pretty promising.

Hopefully, he can keep up the tip a week format. Allegedly, he has 150 tips so he should be good for 3 or so years.

Add a comment
Category: editor Tags:

Lisp Fun

Interested in learning Lisp? A new site has launched with screencast episodes about developing an application in Lisp. The site is LispCast and so far there are three videos up. It's about building a web application that is a clone of Reddit. The subject of the videos so far are writing it, developing tests and refactoring. They each clock in at about twenty minutes and are quite helpful.

It looks like the creator, one Eric Normand, has some pretty big plans for the site. Let's hope that he is able to do it. I know I'm rooting for him.

Add a comment
Category: programming Tags:

Intellij IDEA and Linux: Not Like Peanut Butter and Chocolate

I love me some Intellij and I love me some Linux. Unfortunately, they don't play too well together. Lots of keyboard shortcuts do operating system commands.

For instance, CTRL+ALT+L reformats your code in Intellij but it never gets a chance to that because that keyboard sequence locks the desktop on Ubuntu. Besides changing quite a few keyboard shortcuts in the administration screen, does anyone have any tips or tricks?

Add a comment
Category: editor Tags:

Editing Huge Amounts of Files Easily

Where I work, we have tons of static html files that are published using our custom built Content Management System. Sometimes, we have to change a single line on every single page. For example, the latest case involved a change involving the size of ads that were on the pages. Rather than use publishing and database resources just to make this relatively simple change, I use the power of the shell. Specifically, I use find, sed and a shell script that I wrote. It's based on a shell script in the Unix Power Tools book.

First off, we need to find all the files. I usually accomplish this with something simple like

$ find /www -type f -name "*.html" -print

This simply finds that end with .html in the /www directory. You can do more complex things with find like find all files modified in the last 2 days by Frank if you needed to change files like that.

The results of this will be passed off to a file named located in my ~/bin directory. is reproduced here:

echo -n "editing $1: "
if test "$1" = sedscr; then
    echo -n "Not editing sedscript!"
elif test -s $1; then
         sed -f sedscr $1 > $temp
    if test -s "$temp"; then
        if cmp -s "$1" $temp; then
            echo -n "FILE NOT CHANGED: "
            # save original, just in case
            # mv $1 $1.bak
            cp $temp "$1"
        echo -n "done"
        echo -n "Sed produced an empty file \
- check your sedscript".
rm -f $temp

So, the command we would run would now look like this:

$ find /www -type f \
      -name "*.html" \
      -exec ~/bin/ {} \;

This does the same as above but passes each file found by the find command above to the ~/bin/ script.

You'll notice that the file calls sed using a file named sedscr. The next step is creating the sedscr file.

The sedscr files simple contains sed commands. It must exist in the same directory that you call the find command above from. Here's a sample sedscr that just does a simple replace.


You can enter in as many complex sed commands as you want. It's sed so the power is there!

This simply replaces all instances of BigHonkingAd with NiceSmallAd in each of your files found by the find command. The nice thing about the script is that it will not edit the file if the contents of your sedscr don't produce an altered file. Also, if you want the to make a backup of your original file, just uncomment the mv line.

Using this methodology, I'm able to edit about 5000 files a minute. It could probably be faster if I used xargs and the output of is a little verbose but this solution has worked for me for years and if it ain't broke, why fix it?

Add a comment
Category: programming Tags:

Vim Tip: Select Column

Columns in vim

How many times have you wanted to replace a column of text with something. With vim it's easy. Just use CTRL-V to select a column using a visual block.

Once it's selected, you can do a search and replace, yank, cut and other actions. For example, here's the keystrokes to change a column.

  • Put cursor and beginning of text to select
  • Press CTRL-V to begin select of the column
  • When you reach the end of your select, type 'c'
  • Type the new text. Note that this will only replace the first instance.
  • Now hit <ESC><ESC>. All the text has been changed!

The same thing works with plain old 'v' (select character by character) and SHIFT-V (select by line).

Happy vimming!

Add a comment
Category: editor Tags:

Just Cuz'

OK, I've decided that the next programming langauge I learn is Lisp. I just love all the parenthesis I guess. An excellent Lisp tutorial is Peter Siebel's book Practical Common Lisp.

Fun stuff.

Add a comment
Category: personal Tags:

Command Line Fun

If you use the command line in bash, you should check out the CDPATH environment variable. It'll make your life tons easier.

From the bash man pages, CDPATH is defined as:

The search path for the cd command. This is a colon-separated list of directories in which the shell looks for destination directories specified by the cd command. A sample value is “.:\~:/usr”.

In my .bashrc, I've got the following defined: CDPATH='.:..:../..:~/projects'

This allows me to just type cd app when I want to go to ~/projects/app. Another great part of it is that if I am in /var/log and want to go to /var/www I only need to type cd www. The .. in the CDPATH takes care of finding it.

The important part of it is the first one. The single period allows for cd to work normally and find directories in your current directory.

Add a comment
Category: shell Tags:

Ten Keyboard Shortcuts for IntelliJ IDEA

IntellJ Shortcuts

For my day job I use Java quite a bit. And to edit I use IntelliJ IDEA. I used to use Eclipse but work paid for an IntelliJ IDEA license and I've become hooked. The refactorings and clean interface are a boon to my productivity.

Well this post isn't an IntelliJ IDEA fanboy post so let's get back on track. Here's a list of shortcuts that I find most helpful for use with IntelliJ IDEA. Note that these aren't the obvious ones (like Alt-Space for code completion). These are some hidden ones that you might not know about it.

Comment out the selected lines with //.
Copy the current line and paste it.
Delete the current line.
Delete to word end from cursor.
Delete to word start from cursor.
Select the current word. Press it again and it selects more of the code block.
Run the configuration
Debug the configuration
Find usages of the current word
Bring up the Live Template context menu. If you don't know about Live Templates, you can save major keystrokes by defining them.

For a complete list of keyboard shortcuts for IntelliJ IDEA, there's a PDF issued by JetBrains floating around.

Add a comment
Category: editor Tags:

Linux Cut and Paste

Linux logo

Since I'm in the process of switching to Ubuntu I've been hunting down tips and tricks. One great resource is the Ubuntu Blog. Today they had a great tip for copying and pasting in GNOME.

Basically, what you do is highlight the text in one application (for example Firefox), switch to another application and then click the middle mouse button where you want the text to show up. Your highlighted text is now exactly where you want it. If you don't feel like using the mouse, you can use Shift+Insert in the second application to paste the text.

Add a comment
Category: shell Tags:

Cygwin And SSH Tip

cygwin logo

Auto completion for ssh under cygwin was driving me nuts. It wasn't parsing the ~/.ssh/known_hosts file like it should have and using those values to auto-complete. Investigating, (by using ssh -v) I found out that my known_hosts didn't exist in ${HOME}/.ssh and ssh was using the one in C:/Documents and Settings/smason/.ssh. Uh, excuse me? My $HOME is /home/smason. I cd ~ and I'm in /home/smason. Bafflement ensued.

Turns out my /etc/passwd was all mucked up. It had my HOME directory set to the one in my Documents and Settings directory. I manually edited my /etc/passwd and now ssh auto completion works.

Wow, the second post in a row dealing with auto completion. I guess I really like auto-completion. Think of the keystrokes I'm saving you!

Add a comment
Category: shell Tags:

.bashrc Fun With Subversion

Do you use Subversion a lot from the command line in bash? Then this tip is for you.

Add the following to your .bashrc

# svn completion
_svn ()
    local cur prev
    if [ $COMP_CWORD -eq 1 ] || [ "${prev:0:1}" = "-" ]; then
        COMPREPLY=( $( compgen -W 'add blame cat checkout cleanup \
        commit copy delete diff export help import info list lock \
        log merge mkdir move propdel propedit propget proplist \
        propset resolved revert status switch unlock update' $cur ))
        COMPREPLY=( $( compgen -f $cur ))
    return 0
ccomplete -F _svn -o default -X '@(*/.svn|.svn)' svn

Save your .bashrc, source it (using source .bashrc) and now Subversion commands will complete. For example, enter svn upd press the Tab key and you'll get svn update.

Think of all the keystrokes you'll be saving.

Update: I just found Subversion's own bash completion script which has a ton more options. Mine is easier to maintain. :)

Add a comment
Category: shell Tags:

Got Ugly SQL?

SQL Formatter screen shot

Sometimes you have a bunch of SQL statements that are very long, very verbose and very unreadable. Would you spend minutes of your time to format the SQL in strings so that it's readable? Would you paste the ugly SQL in your source code letting some future maintainer try and decipher it? Well, I'm about to save you a metric ton of time as well as your reputation with maintainers of your code. Use SQL Formatter and it'll do all the grunt work for you.

It's bloody easy to use. Just Accept the usage agreement, paste in your offending SQL statement and choose the formatting and output you want. Bingo! Nicely formatted SQL. You can even choose to format it as a string in the language of your choice so you can just copy and paste it into your source.

If you don't feel comfortable using an online tool, there's a desktop version that's postcardware.

Give it a whirl!

Add a comment
Category: programming Tags:

Keeping It Real Safe And Real Easy

Subversion logo

OK, I've fallen in love with putting my home directory in Subversion. The benefits are enormous. They include (but are not limited to):

  • ease of setting up environment on new system
  • backup
  • ability to go “back in time” using Subversion tags

Mind you I don't put everything in there, just the important stuff like my shell configuration files and my vim configuration files. Other important files (like pictures and music I spent ages ripping) are backed up in other ways.

Here's what I currently have saved in svn:

$ svn ls http://my.svn.server/svn/home-dir/trunk/

So now when I'm on a system, I'll have the same look and feel and same functionality as the utilities I use will be available in my ~/bin directory.

For those astute readers, you'll notice that I don't have a .vimrc file in there. That's because I'm using an excellent tip from Amir Salihefendic about taming your vim config. Basically on each system I have a specialized but simple .vimrc that sources the vim_local for what it needs.

I've found this setup works great on the many different systems I use throughout a given week (e.g. Windows, Mac and Linux). And I'm safe in the knowledge that my configuration files won't disappear should my machines suddenly implode.

Add a comment
Category: tools Tags:

Debugging Is Sexy Good Times

I love me some JSON. The problem with it is that it's not too human readable when you need to see what it's returning. Sure you could litter your code with alerts or console.debug (if you are using Firebug and Firefox to figure out what values are you getting back.

But if you've got the Firefox/Firebug setup (and why don't you if you don't?) then you can just use the Firebug console to display the JSON data. Say for instance you have the following data returned from your service (but imagine it's a bazillion lines long):

               "SubObject": {"SubAttrib1":"bar"}

Just wrap that in an eval function, plug it into the console and you get back a nice little tree of your data in the DOM view.

console screencap

Now isn't that sexy?

Add a comment
Category: programming Tags:


Hello and welcome to This site is basically an experiment to set up a site that's a resume of sorts. It will feature articles about technology that reflect my depth of knowledge.

The site itself is set up using TextPattern. Normally, I would eat my own dog food and use a Java based content management system but I wanted to give PHP and Textile a test. So far, I'm impressed.

For more information about myself, check out my about page. And feel free to leave a comment.

Add a comment
Category: personal Tags:

Writing Tests For Fun And Profit

Learning a new programming language historically starts off with the classic “Hello World” example. I've probably written a variation on that a bazillion times. From there you take more steps into advanced parts of the language. If you are smart, you save your example programs to refer back to them later. But there's a better way. And that better way is to write test cases that exercise the capabilities of the language you are trying to learn. This also works for new libraries within a language you are trying to learn.

The advantages of writing test cases are plentiful. It gets you writing actual code which helps you remember, they can be usually be run easily, they serve as an extra source of documentation about what you are trying to do (e.g. “How do I use gsub again? Oh yeah, it's in that string test I wrote?”) and finally writing tests is fun.

An Example

After ignoring it for way too long, I recently started trying out the Yahoo! User Interface Library. It's a JavaScript library with scads of useful utilities for buidling web applications. So, I pulled up the documentation and started writing a tests based on what's documented. Since it's JavaScript, I used JsUnit since I'm used to JUnit on the Java side of things. And voila we have our first test:

    <title>Test Yahoo</title>
    <script type="text/javascript" 
    <script type="text/javascript" 
    <script type="text/javascript">
        function testIsArray() {
    A test document.

(I know it's very simple but I just wanted to get a feel for the first method in the global library and type it so my brain remembered it.)

So, now I drop the test file into my test runner and here we have the results:

It's all green!

Can't you just feel your brain expanding with the possibilities?

Add a comment
Category: programming Tags:

© Seth Mason

Themed using aboutwilson

Powered by Pelican