Pages

March 1, 2006

JavaScript Applications, pt 2

Updated: Continued in pt 3, Optimization and Compilers

As my last post on this topic was remarkably content-free (by that I mean technically :)) for an article of its size, I thought I'd make this one a little denser. There's nothing I'll cover that's not in most every JavaScript tutorial of any sanity or advancement, but hopefully I can help make the "why?" a little clearer when all is said and done.

First, by way of some definitions, JavaScript is a strong, dynamically typed language. By that I mean that variables can be assigned, well, anything, and each "thing", during run-time, knows explicitly what type it is. We would say a compiled language like C is a weak, statically typed language because types are enforced at compile-time, and "things" don't implicitly know what type they are (e.g. you can forcibly change and/or override "types" in C).

JavaScript, like most dynamically typed languages, is generally an interpreted language. Resolution from instruction to machine code happens during program execution, usually through explicit (i.e. software decoded) instruction dispatching. I say "generally" because compilers like Flash (yes, the Flash authoring tool is a JavaScript compiler) and JScript.NET show that it doesn't HAVE to be an interpreted language. Still, there are limits to what a compiler can do because the dynamism implies that much of the object information is only available at run-time.

From a performance perspective, JavaScript (as in the browser) is
500 to 1000 times slower than compiled C code. To put that in context, imagine your 5 GHz Pentium IV ran at the same speed as your 4.77mhz original IBM PC. Yes, the one with 4 colors, and a 40x25 character display (ok, 80x25 in "high-res" mode). In practice, the delta is somewhat offset by the fact that the rich display engine, parser, and ancillary high-level functions connected to the interpreter run muuuuuch faster than anything your 4.77mhz 8086 PC could do.

The Microsoft JScript interpreter in IE and the Spider Monkey interpreter in Firefox run at about the same speed,
roughly. Each are faster at some basic computing tasks, though I'd give the edge to IE hands down, performance-wise. Conversely, DOM access in Firefox seems faster, while layout and display in IE is usually better. So it all tends to wash out in the end - performance-wise. Incidentally, in some special cases, JScript.NET and the like (as in, like Flash 8.5) can do significantly better, but those paths have their own VERY hidden traps (which I'll explain some examples of in detail in a future post).

JavaScript has some nice attributes:
- Its truly dynamic: no compiler, easy to learn
- Error resistant: it generally just keeps working
- Ubiquitous runtime: the browser, et al
- Flexibility: simple rules, complex patterns, e.g. functions are objects
- Standardization: ECMA 262 - Javascript is often called "ECMAScript"

And on the downside:
- Its truly dynamic: no compiler - means no compile time errors
- Error resistant: it generally keeps working - which makes design holes hard to find
- Ubiquitous runtime: except its buggy as crap-all
- Flexibility: simple rules, complex patterns, e.g. functions are objects - what does that actually mean?
- Opaque costs: performance and memory (hah! - you thought I was going to say "Standardization" :P)

There's a lot of power afforded in the dynamism of the language. It allows for very flexible design patterns (remember we discussed that
notion?), as with function callbacks for example, which are common in UI development.

In JavaScript, you can do things like:
(notice the DYNAMIC internal/nested function definitions)

function myFunc(a)
{
if (a==1) {
function internalFunc(b) {return a+b;}
}
else {
function internalFunc(b) {return a*b;}
}
return internalFunc(a+a);
}

v1 = myFunc(1); //v1 = 3
v2 = myFunc(2); //v2 = 8


Let's parse this in a bit more detail, because it captures much of the problem and opportunity in JavaScript.

First, you should understand that declaring a function is no different than declaring a variable, and has all of the associated
scoping rules in effect. What this means is that "function myFunc(a) {...}" is really the same as "myFunc = function(a){...}" - its JUST a declaration of a function object and assignment to a global variable, in this case "myFunc".

A lot of the confusion arises from the abstraction of dynamic execution on top of (essentially) C-like syntax. Although functions in JS look like blocks of executable code (in the compiled-once, block-of-memory sense), they're really just dynamic objects. And when you declare a nested function, as we did above, the assignment of that function to the locally scoped variable "internalFunc" happens during each and every execution of the function. So why is this a problem?


Two factors make this an issue.

One, JavaScript is a dynamic language, as we said. Even properties on objects are strongly, dynamically bound. Translation? Each instance of each variable on each object creates a property pair hashtable entry on that object. The memory usage can grow quickly. It can
easily be more than 64 bytes for property assignments, PER property, PER object instance, NOT counting the length of the property string itself.

Two, as noted in this
basic tutorial on object-oriented JavaScript programming, here's how you might make a simple, custom JS object:

function Circle(radius) {
function getArea() { return (radius*radius*3.14); }
function getCircumference() { return (radius*2*3.14); }
this.radius = radius;
this.getArea = getArea;
this.getCircumference = getCircumference;
}

var c = new Circle(5);

See the problem?
This code will essentially create locally scoped variables in the stack frame (the nested functions) and assign them to dynamic properties each time this "Circle" object is created. That is, although the inner functions are not PARSED each time you create a "Circle", new instances of the inner functions are assigned to new dynamic properties on the new object instance EACH time you construct the object, wasting both time and space.

JS has a built-in solution to this, called the "prototype" property, and I'll discuss how that works - and how its different and distinct from class derivation. Part of understanding the distinction, in the trivial case, comes from the (obvious) understanding of basic JS optimization, that:


for (i=0; i<100; i++) a.b.c.d(v);

...is a lot slower, at least in JavaScript, than:

var f=a.b.c.d;
for (i=0; i<100; i++) f(v);


...because after all, JS is a dynamic language. I'll provide some specific JavaScript performance tips and JavaScript benchmarks to make the points clearly.

More soon(-ish).

20 comments:

andyc said...

Windows Performance is very important with regard to the running of programs.

Anonymous said...

modern abstract art sofa manufacturer 净水器 混合机 过滤机 DHL快递 俄罗斯签证
保险箱 法兰 法兰标准 polycarbonate sheet 回流焊 波峰焊 免烧砖机 注册上海公司 代孕
牛皮癣 皮肤病
北京快递公司 北京国际快递
传世私服 传奇世界私服
新开传世私服 传奇私服
天龙八部私服 天龙私服
网络电话 免费网络电话
假发 补发
织发 植发
压滤机 板框压滤机
蒸馏水机 纯蒸气发生器
上海搬家公司 上海搬场公司
大众搬家 大众搬场
张家界旅游 香港旅游
深圳旅行社 打包机
收缩机 对讲机
血管栓塞剂
手机监听器
手机窃听器
萎缩性胃炎 neoprene laptop bags
SEO优化
SEO优化 计量泵
胃炎 胃病
冷水机 冰水机
工业冷水机 代写论文 代写论文
北京办证 办证
北京特价机票 北京打折计票 北京国际机票 北京机票预定 北京飞机票 北京订机票 北京机票查询 饮料机械
血糖仪 血糖仪 银杏 水培花卉 企业宣传片 空分设备 机电设备安装
代孕 代孕网
代孕 代孕 代孕 试管婴儿 代孕 电话交换机 程控交换机 集团电话 集装袋
混合机混合机 混合机捏合机 捏合机 捏合机导热油炉 导热油炉 导热油炉 反应釜 反应釜 反应釜
spherical roller bearing
搬运车 搬运车 电动搬运车 油桶搬运车 堆高车 电动堆高车 半电动堆高车 堆垛车 高空作业平台车 电动叉车 平衡重叉车 前移叉车 电瓶叉车
韩国饰品批发 代写论文 代写论文 代写代发 论文代写 电源模块 模块电源
X架 超薄灯箱> 易拉宝 展柜制作
代理服务器 游戏加速器 网络加速器 网通加速器 电信加速器 电信网通转换器 电信网通加速器 网通电信互转 网通电信互通 网络游戏加速器 美国VPN代理 美国独享VPN 美国独享IP
pvc ceiling panel Spherical roller bearings
SEO优化
安全鞋 劳保鞋 防砸鞋 电绝缘鞋 上海安全鞋 上海劳保鞋 江苏劳保鞋
服装软件 服装管理软件 进销存软件 进销存管理软件 服装管理系统 服装进销存软件 进销存系统 进销存管理系统 免费进销存软件
吉林中医 东北特产
打包机 dhl
阳痿 阴茎短小 阴茎增大 早泄 前列腺炎 阴茎增粗 阴茎延长
国际机票 上海国际机票 国际打折机票 国际特价机票
CRM 客户管理软件 客户关系管理 免费客户管理软件 客户管理软件下载 客户信息管理系统 销售管理系统 销售管理 CRM系统 CRM软件 客户关系管理系统 客户关系管理软件 客户管理 客户管理系统 营销管理系统 客户资源管理 销售管理软件 客户资料管理软件 客户资源管理软件 客户信息管理软件 客户资料管理 客户资源管理 客户信息管理 客户资料管理系统 客户资源管理系统 客户管理软件免费版
砂磨机 砂磨机 砂磨机 卧式砂磨机 卧式砂磨机 卧式砂磨机 三辊研磨机 三辊研磨机 三辊研磨机 混合机 混合机 混合机 锥形混合机 锥形混合机 锥形混合机 行星动力混合机 行星动力混合机 行星动力混合机 无重力混合机 无重力混合机 无重力混合机 干粉砂浆设备 干粉砂浆设备 干粉砂浆设备 捏合机 捏合机 捏合机 导热油炉 导热油炉 导热油炉 反应釜 反应釜 反应釜 搪玻璃反应釜 搪玻璃反应釜 搪玻璃反应釜
乳化机 涂料设备 干混砂浆设备 无重力混合机 胶体磨 涂料成套设备 双螺旋混合机
北京婚庆 北京婚庆公司
400电话
办证 呼吸机 制氧机
亚都 亚都加湿器 亚都净化器 亚都装修卫士
饰品批发 小饰品批发 韩国饰品 韩国饰品批发 premature ejaculation penis enlargement
破碎机 制砂机 球磨机 雷蒙磨 雷蒙磨粉机 鄂式破碎机 鄂式破碎机 免烧砖机 加气混凝土设备 反击式破碎机 选矿设备
安利产品 马来西亚留学
网站优化 网站推广
衬布
代写论文
代写论文
论文代写 代写论文 代写硕士论文 代写毕业论文
磁力泵
离心泵
化工泵
隔膜泵
螺杆泵
潜水泵
油泵
耐腐蚀泵
水泵
拖链 防护罩 排屑机 塑料拖链 钢铝拖链
水泵
磁力泵
隔膜泵
离心泵
液下泵
自吸泵
多级泵
排污泵
螺杆泵
油泵
化工泵
电动隔膜泵
气动隔膜泵
自吸式磁力泵
氟塑料磁力泵
管道离心泵
导热油泵
深井泵
潜水泵
污水泵
潜水排污泵
深圳装饰 深圳装饰公司 深圳装修公司
特价机票 打折机票 国际机票 机票
新风换气机 换气机 立式新风换气机 风机箱 新风系统 能量回收机
搅拌机 混合机 乳化机 分散机
毛刷 毛刷辊 工业毛刷 刷子 钢丝刷
涂层测厚仪 硬度计
兆欧表 激光测距仪
测振仪 转速表
温湿度计 风速仪
超声波测厚仪
粗糙度仪
噪音计 红外测温仪
万用表
硬度计 万用表
美容院 美容加盟
澳洲留学 澳大利亚留学
什么是法兰
电烤箱
酒店预定 北京酒店预定 北京酒店
离心机
nail equipment nail products nail product nail uv lamp nail uv lamp nail uv lamps uv nail lamp nail brush nail file nail tool nail tip nail gel curing uv lamps lights
万用表 风速仪
红外测温仪 噪音计
苗木价格 苗木信息 标牌制作 深圳标牌 儿童摄影 北京儿童摄影 防静电鞋 淘宝刷信誉
威海凤凰湖 威海海景房 大庆密封件
打标机 淘宝刷信誉 TESOL/TEFL国际英语教师证书 英语教师进修及培训

Unknown said...

FX・外国為替証拠金取引の比較サイト「FX-外為比較.com」では、複数の条件からFX外国為替会社の比較!また資料請求、口座開設もできます。クレジットカード 現金化にはカード個人信用を著しく落とすシステムが殆どですが、ヤエスチケットのシステムの場合は利用カードと指定商品との安全性や相性を長年のデータとノウハウを熟知しており、安心で信頼できるしっかりとした方法でご案内しています。

fuji said...

A guide to golf courses across the country are available. Terms of ゴルフ会員権and the number of members and annual membership fees,charges and other visitors are also listed. When the bubble to purchase expensive golf club memberships, and now you can not sell if the income tax can be refunded. JPY 52500 ※ fees, but also the total annual income is considering a review, so you do not you think the sale of the golf course, if you measure early! ! Kanto KUORITIGORUFU the business of golf club memberships are a member cooperatives. You can trade with peace of mind. Deals with golfclubmembershipsnationwide. Now, if you want to scan the left toll-free at please feel free to contact us.お取り寄せグルメ on request Gourmet shochu, Muse,specialty products Iki, a "special Iki House homeland." Gourmet site you requested "special Local Museum Iki," Iki壱岐島dearly love to come from sites that are really good. Iki typical graduate, will be a really good product to sell
Interior オーガニック grocery [JURGEN LEHL] online shop, the interior of the tea and organic grocery YOGANRERU handling of the mail-order interior organic grocery [YOGANRERU] online shop furniture, hand towel, soap and other organic tea daily More comfortable to live in the interior of the grocery deals.

fuji said...

ドロップシッピング Q
復縁 Q
豊胸
インプラント Q
引越 Q
ローン
お見合いパーティー
オーク
外壁塗装 Q
三井ダイレクト Q
フロアコーティング Q
ウェディング Q
マンスリーマンション

Charmingirl said...

Wholesale lingerie directly from China?
As a famous brand and specialized manufacturer of sexy clothing in China. Charmingirl supply the international market with fashionable sexy lingerie and sexy costume since 2002. With advanced technology,all our products are of high quality. Now we have clients all around the world. Lingerie Wholesale and OEM are welcomed!
As a Lingerie Manufacturer, Charmingirl has standard workshop and production line, professional designers and experienced workers.
We do Wholesale Underwear,
Lingerie Wholesale, including corset and bustier,
Sexy Lingerie Wholesale, including bikini, underwear
Lingerie Wholesale, and Babydolls, Sexy Lingerie Wholesale, and
Sexy Lingerie Wholesale including sleepwear,clubwear.
Lingerie Wholesale from China: Lingerie China, you will find the
Leather Lingerie and PVC Lingerie, also you can buy
Christmas Costume and Xmas Lingerie
for your Christmas Lingerie Christmas day.
Our Wholesale center: Sexy Lingerie Wholesale can do Lingerie Wholesale online.
Halloween Costume,
also wholesale Adult Costume with fashion Babydoll Babydoll, and bra and panties Bra and Panties, Sexy Uniform Sexy Uniform is also our major products.

Anonymous said...

ショッピング枠現金化するので誰でもかんたんにカードでお金をおつくりできます♪ご融資などではありませんので審査や面倒な手続きは一切ございません! ご返済方法は一括・リボ・分割(最高20回)・ボーナス一括などからお選びいただけます。当店は女性スタッフも対応しております。ご利用方法などはお気軽 に。ご利用の可否、ご利用詳細など安心・丁寧をモットーに即回答しています。急場の資金つくりにお役に立てるサポートをさせていただきます

Anonymous said...

Today, in-gamthe Microsoft-owned e ad agency said that it has signed an exclusive multiyear agreement with Blizzard. Azerothians opposed to seeing in-game ads in their localworld of warcft goldwatering holes need not worry, however, because the deal is limited to Blizzard's Web sites and Battle.net,the game maker's online-gaming hub. Terms of the deal were not announced, but Massive did note that the agreement is applicable to users in the US, Canada, Europe, South Korea, and Australia.
buy wow gold


Massive also said today that it would be extending its aforementioned deal with Activision to encompass an additional 18 games appearing on the Xbox 360 and PC.cheap wow goldThe agency didn't fully delineate which would fall under this deal, though it did call out Guitar Hero: World Tour, James Bond: Quantum of Solace, and Transformers: Revenge of the Fallen,buy wow items as well as games in its Tony Hawk and AMAX Racing franchises.Shortly before Activision and Vivendi announced their deal of the decade,wow power levelingthe Guitar Hero publisher signed on to receive in-game advertisements from Massive Inc for a number of its Xbox 360 and PC games. A bit more than a year later, Massive is now extending its reach to Activision's new power player, Blizzard Entertainment.buy wow gold from our site ,you'll get more surprises

Anonymous said...

鍵屋なら、プレスリリースなら、ウォーターサーバー 比較なら、ウォーターサーバー ランキングなら、FXなら軽貨物なら、おまとめローンなら、債務整理とは、任意整理なら、POS システムなら、ウォーターサーバー ランキングなら、ニュースリリースなら、DM発送代行なら、自動販売機設置なら、過払いとは、キャッシングなら、FX比較なら、おまとめローンです。!

Anonymous said...

naturum slmame soreccha junglekouen i-yoblog mie1 da-te.jp hama1.jp eshizuoka.jpkitaguni.tv livedoor.jp gifulog diary.ne.jp tenkomori.tv kurdblogger j-breeze.jp hamazo.tv namjai saitamania slashdot.jp blog126.fc2 sun.ap.teacup tvblog osakazine tencho

Anonymous said...

コンタクトレンズ
幼児教室
toefl 
個別指導塾
システム開発
合宿 免許
債務整理
多重債務

Unknown said...

蜂王浆
芦荟
蜂胶

ball valve球阀
gate valve闸阀
angle valve角阀
bibcock水嘴
tap
Check valve
hot-water heating
fittings
苏州led
上海led
北京led
苏州电磁铁
苏州装修公司
苏州装饰公司
ats


双电源切换开关
双电源转换开关
双电源开关
乐清网站推广.

乐清网站建设.

Anonymous said...

出会い
出会い
セフレ
メル友
人妻
出会い
出会い系
メル友
セフレ
人妻
恋人
不倫
セックスフレンド
出会い
ご近所
出会い
メル友
出会い系
人妻
出会い
結婚童貞
セフレ
スタビ
援助
ギャル
熟女
メル友
出会い系サイト

Anonymous said...

名刺 ne2ying
探偵 感觉4ying
ショッピングカート 3ying
フロアコーティング
お見合いパーティー jepying

Anonymous said...

qwo
wer
to
for
live
hi
sky
per
cou

Anonymous said...

別れさせ屋
横浜デリヘル
オナホール
大阪 ホスト
アダルトグッズ
デリヘル
デリヘル 品川
吉原 ソープ
デリヘル
熟女
横浜デリヘル
アダルト
アダルト動画
出会い
出会い

Anonymous said...

toefl
幼児教室
合宿 免許
個別指導塾

Anonymous said...

Looking for China Baskets, Wholesale Baskets? We provide latest cheapest fashionable baskets wholesale from China at discount wholesale price: Plastic Basket, shopping bags, Rattan Baskets, colorful basket, Plastic Basketry, Gift Baskets, Wicker Baskets, bread Basket, flower basket,
Need Overstock products, from China? Stock Underwear, underpants, men panties, stock jeans, stock garment, denim jeans, Lee Jeans, Stock Blanket, Mattress Cartoon Blanket, Stock Polyester Blanket, Cartoon Blanket, mickey blanket,
Some Promotional Gifts such as led flashlight, Led reading lamp, Mini reading lamp, table lamp, Rechargeable led lamp, Aluminum LED Flashlight,
Wholesale shoes, Wholesale boots, Wholesale sneakers, Wholesale casual shoes, Wholesale dress shoes, Wholesale sandals, Wholesale slippers, from Yiwu, good quality, for all your cheap wholesale needs, your one stop China suppliers. Start your one stop China discount wholesale sourcing here today and experience top notch service and fast shipping. Welcome to Yiwu China to buy China wholesale products all at lowest wholesale price on http://www.AmandaIEC.com.
Browse Alphabetically: A?B?C?D?E?F?G?H?I?J?K?L?M?N?O?P?Q?R?S?T?U?V?W?X?Y?Z?0-9

Anonymous said...

I can get ro zeny cheaply,
Yesterday i want to buy ragnarok zenyfor my brother.
i hope him like it. i will buy iro zeny for him
as birthday present. i like the cheap zeny very much.
I usually buy ragnarok online zeny and keep it in my store.

Anonymous said...
This comment has been removed by a blog administrator.