<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>NIX/WIN/WEB &#187; Web</title>
	<atom:link href="http://www.formboss.net/blog/category/web/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.formboss.net/blog</link>
	<description>Modern Web Application Development</description>
	<lastBuildDate>Thu, 02 Feb 2012 18:43:36 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Thoughts On SOAP/PIPA And The Future Of The Net.</title>
		<link>http://www.formboss.net/blog/2012/01/thoughts-on-sopa/</link>
		<comments>http://www.formboss.net/blog/2012/01/thoughts-on-sopa/#comments</comments>
		<pubDate>Wed, 18 Jan 2012 19:49:03 +0000</pubDate>
		<dc:creator>grdinic</dc:creator>
				<category><![CDATA[Web]]></category>
		<category><![CDATA[PIPA]]></category>
		<category><![CDATA[Software Owner]]></category>
		<category><![CDATA[SOPA]]></category>

		<guid isPermaLink="false">http://www.formboss.net/blog/?p=1550</guid>
		<description><![CDATA[SOPA and PIPA are bills are designed to help guys like me (software company owners), and yet I find them pretty distasteful in many ways. As other have pointed out, a rather large burden is placed on site owners, especially those who run aggregate sites like Reddit and YouTube. My understanding is content/copyright owners can [...]]]></description>
			<content:encoded><![CDATA[<p>SOPA and PIPA are bills are designed to <em>help</em> guys like me (software company owners), and yet I find them pretty distasteful in many ways.</p>
<p>As other have pointed out, a rather large burden is placed on site owners, especially those who run aggregate sites like Reddit and YouTube. My understanding is content/copyright owners can request that sites be <strong>removed from the US Internet</strong> if they&#8217;re found to harbor, support, or link to unlicensed content.</p>
<p><span id="more-1550"></span></p>
<p>On the face of it that seems like it makes sense &#8212; if you&#8217;re &#8220;linking&#8221; to stolen goods via a sign in the front yard that says &#8220;car stereos in garage&#8221; it&#8217;s only natural that, even if it&#8217;s not your house, the operation gets shut down.</p>
<p>Right now the Internet is as free as it gets. Virtual goods and ideas exchange &#8220;hands&#8221; with impunity. Be it a movie or your <em>thoughts</em> on the movie, the Internet and our government doesn&#8217;t make a distinction. It&#8217;s all just bits floating in space.</p>
<p>As a society then we have a simple decision to make: <strong>do we embrace the current system or do we throw it away?</strong></p>
<p>If the answer is &#8220;embrace&#8221; content providers and producers will simply have to live with the Internet as it stands right now, pirates and all.</p>
<p>Me: I like to pay for things:</p>
<p><a href="http://www.formboss.net/blog/2012/01/thoughts-on-sopa/itunes-tv/" rel="attachment wp-att-1551"><img class="alignnone size-full wp-image-1551" title="itunes-tv" src="http://www.formboss.net/blog/wp-content/uploads/2012/01/itunes-tv.jpg" alt="" width="650" height="527" /></a></p>
<p>By my rough count I own 144 episodes at $2.99 each making for $432 in TV shows. I also own about 860 songs, which at .99 cents means I&#8217;ve spent close to a thousand dollars on music &#8212; in the past 4 years.</p>
<p>This isn&#8217;t counting the Blurays and DVD I&#8217;ve bought over the years, the movie tickets, and of course rentals.</p>
<p>In short I&#8217;ve still spent what <em>I</em> consider a pretty exorbitant amount of money on entertainment, an amount that in some countries would be the equivalent of a years salary or more.</p>
<p>I pay because feel anything else would be wrong. In fact, my beloved South Park episodes: I can watch those for free anytime I want at <a href="http://www.southparkstudios.com/">South Park Studios</a> and yet I don&#8217;t. Why? I like to own stuff I&#8217;ve paid for I guess.</p>
<p>And yet as sure as you have me and my way of buying, you have others who feel entitled to whatever they want, when they want, and always for free.</p>
<p>Thus, the other option is we do not embrace openness and instead move to lock the Internet down. In this world the Internet will become what I&#8217;ve been predicting all along: the cable TV model but on the Net. Instead of an open model we&#8217;ll buy &#8220;Internet Content Packages&#8221; (channels) that contain blocks of content (that still contain ads, just like cable TV does today!).</p>
<p>So we&#8217;ll get the tech package that contains access to Ars and Vox properties, the sport package that contains ESPN, and so on. I fear smaller sites like mine will be relegated to what in cable TV today is the public access channel. A slower, less reliable data-stream that at best means fewer visitors and less traffic. And make no mistake, we&#8217;ll do this willingly. An effort will be made to make the Internet as dangerous (legally speaking) as can be for aggregates (fan sites, the aft-mentioned YouTube etc), which means the &#8220;good&#8221; content will be the curated stuff we &#8220;conveniently&#8221; pay for in the content packages.</p>
<p>And so as I said above the bill is supposed to help software guys like me (content producers), but in the long term I believe its potential to hurt my business is a real threat.</p>
<p>Put another way I feel the greatest failing of SOPA is its inability to stop piracy in general while fundamentally changing how the Internet works for us working folk. Same as I have my content channel (iTunes) pirates have theirs, disabling websites because of links won&#8217;t stop this at all. Thus, SOPA passes and I, a law-abiding consumer, pays, while the pirates quite literally never do. They&#8217;re already comfortable using illicit channels, what&#8217;s to stop that in the future?</p>
<p>The future of the Internet is not in question &#8211; it&#8217;s what it will look like that is. I personally side with those that argue so long as content is easy to access and comes with reasonable rights <em>people will pay</em>.</p>
<p>I believe their are more than enough of us that fit into this mold, why should we be punished for those that do not?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.formboss.net/blog/2012/01/thoughts-on-sopa/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Where Bing Has To Improve</title>
		<link>http://www.formboss.net/blog/2011/12/where-bing-has-to-improve/</link>
		<comments>http://www.formboss.net/blog/2011/12/where-bing-has-to-improve/#comments</comments>
		<pubDate>Sat, 10 Dec 2011 20:06:05 +0000</pubDate>
		<dc:creator>grdinic</dc:creator>
				<category><![CDATA[Web]]></category>
		<category><![CDATA[Bing Search]]></category>
		<category><![CDATA[Google Search]]></category>

		<guid isPermaLink="false">http://www.formboss.net/blog/?p=1525</guid>
		<description><![CDATA[I appreciate competition in the search engine space but Bing simply doesn&#8217;t compete at this point. I would like to it, but it simply doesn&#8217;t. So let&#8217;s talk why: When building something like FormBoss you often run into a situation where you need to do cross-browser compatibility coding. With Google Chrome now in the #2 [...]]]></description>
			<content:encoded><![CDATA[<p>I appreciate competition in the search engine space but <em>Bing</em> simply doesn&#8217;t compete at this point. I would like to it, but it simply doesn&#8217;t.</p>
<p><span id="more-1525"></span></p>
<p>So let&#8217;s talk why: When building something like FormBoss you often run into a situation where you need to do cross-browser compatibility coding. With Google Chrome now in the #2 spot and IE variants still holding around 50% of the market, this means at minimum 3 browser windows open at once.</p>
<p>This also means the developer tools for each browser being open and ready for some heavy lifting as code checks are run and bug squashed. Problem is, somehow the IE developer tools are not pinned to the main window like Chrome and Firefox, which means I&#8217;ve got an extra window clogging an already tight workspace.</p>
<p>I need to pin them to the IE window, but do not know how. As I&#8217;m already in IE I <em>Bing</em>:</p>
<pre>ping ie developer tools to main window</pre>
<p>I know, I know : ) My spelling&#8217;s terrible, but that&#8217;s the whole point.</p>
<p>I miss my error at first, and my search results comes back with this:</p>
<p><a href="http://www.formboss.net/blog/2011/12/where-bing-has-to-improve/bing-results-1/" rel="attachment wp-att-1526"><img class="alignnone size-full wp-image-1526" title="bing-results-1" src="http://www.formboss.net/blog/wp-content/uploads/2011/12/bing-results-1.png" alt="" width="655" height="694" /></a></p>
<p>Not to be a mean guy, but that&#8217;s utterly worthless as a search result. It&#8217;s not even close that what I need or want.</p>
<p>So I copy/paste my #erroneous# query into Google and get this:</p>
<p><a href="http://www.formboss.net/blog/2011/12/where-bing-has-to-improve/google-results-1/" rel="attachment wp-att-1527"><img class="alignnone size-full wp-image-1527" title="google-results-1" src="http://www.formboss.net/blog/wp-content/uploads/2011/12/google-results-1.png" alt="" width="605" height="708" /></a></p>
<p>Eureka. Three completely relevant links right up top.</p>
<p>And that&#8217;s the thing. I gave Google what to some <em>humans</em> would be an nonsensical question and yet Google still comes through.</p>
<p>Now to be fair when we change our query to:</p>
<pre>pin ie developer tools to main window</pre>
<p>Bing comes through in fine fashion, even providing a Microsoft link at top:</p>
<p><a href="http://www.formboss.net/blog/2011/12/where-bing-has-to-improve/bing-results-2/" rel="attachment wp-att-1528"><img class="alignnone size-full wp-image-1528" title="bing-results-2" src="http://www.formboss.net/blog/wp-content/uploads/2011/12/bing-results-2.png" alt="" width="636" height="849" /></a></p>
<p>So it&#8217;s not all bad, but I&#8217;ve come to expect that my search engine is smarter than me.</p>
<p>Google is, Bing is not.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.formboss.net/blog/2011/12/where-bing-has-to-improve/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>jQuery vs. Prototype – Part 2</title>
		<link>http://www.formboss.net/blog/2011/10/jquery-vs-prototype-%e2%80%93-part-2/</link>
		<comments>http://www.formboss.net/blog/2011/10/jquery-vs-prototype-%e2%80%93-part-2/#comments</comments>
		<pubDate>Sun, 23 Oct 2011 20:23:12 +0000</pubDate>
		<dc:creator>grdinic</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Prototype JS]]></category>

		<guid isPermaLink="false">http://www.formboss.net/blog/?p=1480</guid>
		<description><![CDATA[In the first post of this series we looked at the common misconception of jQuery being the &#8220;lightweight&#8221; JavaScript library. In this post we&#8217;ll leave the sidelines and jump right into some real-world scenarios. I want to see what makes jQuery tick by comparing it to my beloved Prototype. A quick note as we get [...]]]></description>
			<content:encoded><![CDATA[<p>In the first post of this series we looked at the common misconception of jQuery being the &#8220;lightweight&#8221; JavaScript library. In this post we&#8217;ll leave the sidelines and jump right into some real-world scenarios. I want to see what makes jQuery tick by comparing it to my beloved Prototype.</p>
<p><span id="more-1480"></span><br />
<em>A quick note as we get started: I&#8217;ve never coded in jQuery before, so my apologies ahead of time if I miss something obvious!</em></p>
<h2>A Button Clicking Example</h2>
<p>In this first example let&#8217;s see what a typical event handler for a button click looks like when following the design pattern of separating design from implementation: </p>
<p><strong>Prototype:</strong></p>
<pre class="brush: jscript; title: ; notranslate">
&lt;!DOCTYPE html&gt;
&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;
&lt;head&gt;
&lt;script src=&quot;prototype.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=utf-8&quot; /&gt;
&lt;title&gt;Prototype&lt;/title&gt;

&lt;script type=&quot;text/javascript&quot;&gt;

// bind each button
document.observe('dom:loaded', function(){

	syntax = 'quick';

	if(syntax == 'quick'){
		// quick syntax
		$$('.dynamic-element-wrapper &gt; INPUT').invoke('observe', 'click', buttonClicked);
	}

	if(syntax == 'verbose'){
		// verbose
		$$('.dynamic-element-wrapper &gt; INPUT').map(function(t){
			t.observe('click', buttonClicked);
		});
	}

});

function buttonClicked(e){
	$('console').update(e.element().id + ' Clicked');
};

&lt;/script&gt;

&lt;/head&gt;

&lt;body&gt;

&lt;div class=&quot;dynamic-element-wrapper&quot;&gt;
	&lt;input type=&quot;button&quot; id=&quot;button-1&quot; name=&quot;button-1&quot; value=&quot;Button 1 - Click Me&quot; /&gt;
    &lt;input type=&quot;button&quot; id=&quot;button-2&quot; name=&quot;button-2&quot; value=&quot;Button 2 - Click Me&quot; /&gt;
&lt;/div&gt;

&lt;div style=&quot;clear:both;&quot; id=&quot;console&quot;&gt;&lt;/div&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p><strong>jQuery</strong></p>
<pre class="brush: jscript; title: ; notranslate">
$(document).ready(function() {

	syntax = 'verbose';

	if(syntax == 'quick'){
		$('.dynamic-element-wrapper &gt; INPUT').click(buttonClicked);
	}

	if(syntax == 'verbose'){
		$('.dynamic-element-wrapper &gt; INPUT').bind('click', buttonClicked);
	}

});

function buttonClicked(e){
	$('#console').html(e.target.id + ' Clicked');
};
</pre>
<p><em>Please note that as the HTML doesn&#8217;t change the jQuery code sample is limited to just the SCRIPT block.</em></p>
<p><strong>So a couple items of note:</strong></p>
<p>As a long-time Prototype guy jQuery&#8217;s automatic array return when using $() sits in stark contrast to Prototype&#8217;s use of $$(). I have to admit I&#8217;m torn on this one, as in a way the jQuery way makes more sense. The selector and knowledge of the document, combined with the function our event listeners call should be all that&#8217;s needed from a selector. In practical terms then differentiating between $() and $$() is admittedly more work without a huge gain in readability. </p>
<p>That aside, in Prototype we also get a bit more syntax heavy having to resort to <strong>.invoke()</strong> or <strong>.map()</strong>, whereas jQuery&#8217;s <strong>.click()</strong> makes short work of the job &#8212; providing a quick and concise way to perform such a common task is a huge win.  </p>
<p>On the event processing side our <strong>buttonClicked()</strong> call is very similar. Once again jQuery&#8217;s love of shortcuts impresses me. <strong>.html()</strong> for getting <em>and </em>setting text is quite nice, and from what I can see, is duplicated via <strong>.val()</strong> of the form field side. </p>
<h2>The this Reference Binding Issue</h2>
<p>So here comes the main event. The example above in terms of design pattern is going to be just fine for most projects. Our design code is free from implementation code and when we click the element we get the info we need &#8212; everything just works. </p>
<p>But what happens when we follow a slightly more complex design pattern? Many times allowing UI implementation code to hover in the global script scope is perfectly acceptable. But their are times, either by virtue of space or code cleanliness, that wrapping our event code into objects is desirable or required. </p>
<p>An example of doing so in <strong>Prototype </strong>looks like this:</p>
<pre class="brush: jscript; title: ; notranslate">
var buttonFactory = {

	_limit: 10,
	_secure: true,

	bindObjects: function(){
		$$('.dynamic-element-wrapper &gt; INPUT').invoke('observe', 'click', this.buttonClicked);
	},

	buttonClicked: function(e){
		$('console').update(e.element().id + ' was clicked. ' + 'The limit value = ' + this._limit);
	}

};

// bind each button
document.observe('dom:loaded', function(){
	buttonFactory.bindObjects();

});
</pre>
<p>As you can see instead of binding our event listeners in the global scope we issue a simple call to <strong>buttonFactory.bindObjects()</strong>. If this was a much larger project it&#8217;s not hard to see why this would be a great way to work. Our <strong>document.observe</strong> code would simply be a series of calls to code that initialize other parts of the UI. The initialization code would then perform all sorts of long-winded tasks while leaving our <strong>document.observe</strong> call far from the down and dirty details. </p>
<p>But all&#8217;s not well. When coding this way &#8212; if not just to save space but to also create more complex event handling logic &#8212; we would expect that our <strong>buttonClicked()</strong> code would handle the reference to <strong>this._limit</strong> but it doesn&#8217;t. We&#8217;ll get this when we click a button:</p>
<pre class="brush: plain; title: ; notranslate">button-2 Was Clicked. The limit value = undefined</pre>
<p>That&#8217;s not at all what we want. You&#8217;d think <strong>this._limt</strong> should return with a value of 10 but it doesn&#8217;t. Why? </p>
<p>The problem is when we bound our event listener the <em>this </em>reference wasn&#8217;t part of the process. This means when we trigger a click event the <em>this </em>refers to the <strong>event object</strong>, not the buttons original parent object (buttonFactory). </p>
<p>Prototype has a solution for this via a call to <strong>bindAsEventListener()</strong>. <strong>bindAsEventListener()</strong> takes the object we wish to use as the <em>this </em>reference when invoked. To implement this fix in our example code we&#8217;d change our <strong>bindObjects()</strong> call to:</p>
<pre class="brush: jscript; title: ; notranslate">
//
//
$$('.dynamic-element-wrapper &gt; INPUT').invoke('observe', 'click', this.buttonClicked.bindAsEventListener(this));
//
//
</pre>
<p>Now when we run our code it returns the following when a button&#8217;s clicked:</p>
<pre class="brush: plain; title: ; notranslate">button-1 was clicked. The limit value = 10</pre>
<p>That&#8217;s more like it. Sure this is a synthetic example, but it&#8217;s absolutely essential to creating <em>portable </em>code. </p>
<p>Portable is the key word here, as yes, we could just do this to our <strong>buttonClicked() </strong>call:</p>
<pre class="brush: jscript; title: ; notranslate">
//
//
$('console').update(e.element().id + ' was clicked. ' + 'The limit value = ' + buttonFactory._limit);
//
//
</pre>
<p>But this would be in bad form in my opinion, as now we&#8217;re making all sorts of assumptions of how this object will be consumed. </p>
<p>So the point is Prototype gives us a sleek, consistent way of holding objects together in event-driven code. </p>
<p>How does jQuery solve this issue?</p>
<p><strong>jQuery</strong></p>
<pre class="brush: jscript; title: ; notranslate">
var buttonFactory = {

	_limit: 10,
	_secure: true,

	bindObjects: function(){
		$('.dynamic-element-wrapper &gt; INPUT').bind('click', this, this.buttonClicked);
	},

	buttonClicked: function(e){
		$('#console').html(e.target.id + ' Clicked' + 'The limit value = ' + e.data._limit);
	}

};

$(document).ready(function() {
	buttonFactory.bindObjects();
});
</pre>
<p>The <a href="http://api.jquery.com/bind/" target="_blank">method signature</a> of .bind() as we&#8217;re using it is:</p>
<pre class="brush: plain; title: ; notranslate">.bind( eventType [, eventData], handler(eventObject) )</pre>
<p>Thus, my solution is to simply pass our object reference as the <strong>eventData </strong>argument. We then pick up on the value via the <strong>event.data </strong>object in <strong>buttonClicked()</strong> and away we go. </p>
<p>Seems simple enough but again I do not have&#8230;well&#8230;<em>any </em>jQuery experience, so I would not be surprised is this is wrong in terms of implementation. What I <em>can </em>say though is it works just fine, and once again the syntax is pretty slick. For Prototype adding bindAsEventListener() is every bit as cumbersome as <strong>document.getElementById()</strong> if you catch my drift&#8230;</p>
<p>I say it works fine as for my part I did issue a test call of:</p>
<pre class="brush: jscript; title: ; notranslate">e.data._limit = 20;</pre>
<p> under the <strong>#console</strong> update call and sure enough, the <strong>buttonFactory </strong>object was updated accordingly. From this we can tell <em>this </em>is passed as a reference, which means for my money this is an acceptable, working solution. </p>
<p>For the sake of completeness it appears we can also use <a href="http://api.jquery.com/jQuery.proxy/" target="_blank">.proxy()</a>. </p>
<p>When used our code changes to:</p>
<pre class="brush: jscript; title: ; notranslate">
var buttonFactory = {

	_limit: 10,
	_secure: true,

	bindObjects: function(){
		var bProxy = $.proxy(this.buttonClicked, this);
		$('.dynamic-element-wrapper &gt; INPUT').bind('click', bProxy);

	},

	buttonClicked: function(e){
		$('#console').html(e.target.id + ' Clicked' + 'The limit value = ' + this._limit);
		e.data._limit = 20;
	}

};

$(document).ready(function() {
	buttonFactory.bindObjects();
});
</pre>
<p>I&#8217;m not entirely sold on this method as now we&#8217;re once again in the mode of hand-wrangling specific behavior from our objects. It&#8217;s nice to know it can be done, however.</p>
<h2>Conclusion</h2>
<p>The title of this post has a <em>vs.</em> in it so who wins this round? Somewhat unsurprisingly I think it&#8217;s a draw, though if I had to pick I&#8217;d say jQuery. jQuery&#8217;s ability to pass <em>this </em>as an event parameter and it still works is fine by me and easier to code, and considering we can just as easily wrap <em>this </em>into a larger structure is better still.</p>
<p>Of course I&#8217;m ready and willing to have any and all ignorance corrected, so if you&#8217;ve seen something that&#8217;s not right with my solution(s) please let me know! </p>
<p>The bottom line is jQuery has some real time savers in its bucket of tricks; the fact that $() returns arrays is worth the price of admission alone.</p>
<p>Color me continually intrigued.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.formboss.net/blog/2011/10/jquery-vs-prototype-%e2%80%93-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>jQuery vs. Prototype &#8211; Part 1</title>
		<link>http://www.formboss.net/blog/2011/10/jquery-vs-prototype-part-1/</link>
		<comments>http://www.formboss.net/blog/2011/10/jquery-vs-prototype-part-1/#comments</comments>
		<pubDate>Sat, 22 Oct 2011 18:50:27 +0000</pubDate>
		<dc:creator>grdinic</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Prototype JS]]></category>

		<guid isPermaLink="false">http://www.formboss.net/blog/?p=1449</guid>
		<description><![CDATA[One of the hottest JavaScript libraries on the planet is jQuery. It&#8217;s opened up a world of web developers to functionality and ease they would not otherwise know, and has done so without stepping on anyone toes. Their are hundreds of great extensions for it made by a first-rate community that&#8217;s almost always helpful and [...]]]></description>
			<content:encoded><![CDATA[<p>One of the <a title="http://appendto" href="http://appendto.com/jquery-overtakes-flash" target="_blank">hottest</a> JavaScript <a title="codeclimber" href="http://codeclimber.net.nz/archive/2009/06/22/ajax-survey-2009-jquery-and-ms-ajax-are-almost-tied.aspx" target="_blank">libraries</a> on the planet is jQuery. It&#8217;s opened up a world of web developers to functionality and ease they would not otherwise know, and has done so without <a title="noConflict()" href="http://api.jquery.com/jQuery.noConflict/" target="_blank">stepping on anyone toes</a>. Their are hundreds of great extensions for it made by a first-rate community that&#8217;s almost always helpful and supportive. When it comes to getting a job I&#8217;d say jQuery knowledge is <a title="Stack Overflow" href="http://stackoverflow.com/questions/932967/do-javascript-developers-need-to-know-jquery" target="_blank">almost becoming requirement</a>, if not right away then as part of your integration into that job.</p>
<p>Prototype JS is&#8230;well&#8230;it&#8217;s another JavaScript library. But it&#8217;s the library I know and <em>love</em>. It&#8217;s what drives FormBoss and while not as exciting or popular as jQuery, I swear its day <em>will </em>come (again). Their are many reasons for this belief, but the first is due to what I believe is a fundamental misconception about jQuery vs. other libraries &#8212; its payload size.</p>
<p>In this first of a multi-part series we&#8217;ll take a look at the physical delivery size of each library. In the next post well dive into practical programming. First though, a bit of background.</p>
<p><span id="more-1449"></span></p>
<h2>Background</h2>
<p>As a professional Web Developer I had a decision to make in mid-2008 as to what JavaScript library I would use for FormBoss. At that time I was looking for a library that fixed JavaScript&#8217;s core issues and had good AJAX support. (<em>Little did I know that while AJAX support was important, far more relevant would be DOM handling and event binding, but more on that latter</em>).</p>
<p>I checked a few libraries starting with Yahoo&#8217;s <a title="YUI" href="http://developer.yahoo.com/yui/" target="_blank"><em>YUI </em></a>and <a title="Dojo" href="http://dojotoolkit.org/" target="_blank"><em>Dojo</em></a>. Forget it. Far more complex than I needed, they seemed to make even simple tasks difficult (<em>disclaimer: I haven&#8217;t looked into these libraries for some time now, they may be better, or perhaps my initial impressions were wrong!</em>).</p>
<p>What I really wanted was a library like PHP. Provide a solid foundation that was <em>not </em>unto itself a framework. All I wanted was something that extends and smooths over vanilla JavaScript but also provides glue functions for doing more advanced stuff.</p>
<p>It wasn&#8217;t long before I narrowed my decision down to Prototype and jQuery (at <em> versions 1.6.0.3 and at 1.2.6., respectively)</em>. Both seemed strong &#8211; jQuery on the count of its small size and simplicity, Prototype because of its more robust feature-set and AJAX support (<em>again though DOM traversal and event binding played no part in this process, but would become crucial later on</em>).</p>
<p>In the end I went with Prototype for a simple reason &#8212; it seemed more &#8220;complete&#8221; in terms of a programming construct. jQuery, always bragging about how small it was seemed almost <em>too </em>small, too limiting. I wasn&#8217;t looking for flash but utility, and Prototype fit the mold. For the most part I haven&#8217;t regretted this decision one bit&#8211;in the intervening years Prototype has been wonderful to me and always delights. In places where it needed improvement like upgrading to the Selectors API it&#8217;s done so in a reasonable time-frame, and for just about everything else, such as animation and event binding, it&#8217;s never let me down.</p>
<p>But always in the back of my mind has been jQuery, a nagging sense that I&#8217;m missing something. Why has it gotten so popular and does this mean I should be using it too?</p>
<h2>Modern jQuery &#8211; The Popular Place To be</h2>
<p>The base answer to our question of <em>why so popular</em> can be found right at the top of the jQuery <a title="jQuery" href="http://jquery.com/" target="_blank">home page</a>:</p>
<p><a rel="attachment wp-att-1450" href="http://www.formboss.net/blog/2011/10/jquery-vs-prototype-part-1/get-jquery/"><img class="alignnone size-full wp-image-1450" title="get-jquery" src="http://www.formboss.net/blog/wp-content/uploads/2011/10/get-jquery.png" alt="" width="295" height="218" /></a></p>
<p>Compare that with <a title="Prototype JS" href="http://www.prototypejs.org/" target="_blank">Prototype</a>:</p>
<p><a rel="attachment wp-att-1451" href="http://www.formboss.net/blog/2011/10/jquery-vs-prototype-part-1/get-prototype/"><img class="alignnone size-full wp-image-1451" title="get-prototype" src="http://www.formboss.net/blog/wp-content/uploads/2011/10/get-prototype.png" alt="" width="260" height="68" /></a></p>
<p>Ugh. It&#8217;s no wonder jQuery has more hype &#8212; seriously &#8212; by download link alone jQuery simply looks cooler and more advanced.</p>
<p>But it&#8217;s not just that&#8230;well not entirely : )</p>
<p>When you look at the jQuery download options you see that magic value: <strong>31KB</strong>.</p>
<p>How brilliant can they be? Think about all of those large newspaper, e-commerce, and other highly trafficked sites. Bandwidth is money, and when it comes time to tell your boss you need to add more weight to a site it had better be as little as possible <em>and </em>worth it. More importantly, even as recently as 2009 <a title="FCC Broadband Adoption" href="http://online.wsj.com/public/resources/documents/FCCSurvey.pdf" target="_blank">broadband adoption</a> in America was still only 67%. Sure that number continuies to rise but now consider our rising mobile Internet use. Truly two steps forward and one step back.</p>
<p>The point is size still matters, and Prototype&#8217;s stubborn lack of a minified version and frankly boring site and download page mean of course jQuery&#8217;s flashy site will draw more users in, both from a aesthetic and practical standpoint.</p>
<h2>In Reality&#8230;</h2>
<p>But of course we&#8217;re developers so we go deeper than that, and in preparation for this post I was&#8211;admittedly&#8211;floored by a simple test:</p>
<p><a rel="attachment wp-att-1452" href="http://www.formboss.net/blog/2011/10/jquery-vs-prototype-part-1/relative-sizes/"><img class="alignnone size-full wp-image-1452" title="relative-sizes" src="http://www.formboss.net/blog/wp-content/uploads/2011/10/relative-sizes.png" alt="" width="277" height="314" /></a></p>
<p>Had you asked me just five minutes ago I would have said &#8220;<em>Of course</em> jQuery is smaller, everyone knows that!&#8221;.</p>
<p>As of 1.6.4 jQuery has actually grown larger than Prototype in terms of raw source , 6084 lines vs. 9048 (and almost twice as large in terms of raw source code size in KB). More importantly though is while the minified version of Prototype is still larger, the minified + gzipped versions are <em>identical</em>. More importantly still: the minified jQuery is not 32KB but ~90KB. This is important because the jQuery website makes you feel like you&#8217;ll be getting all of that functionality for 32kb, but <em>only </em>if your server is gzipping content. The simple fact is almost all shared hosting plans won&#8217;t be doing do, which means your 32KB is actually closer to 90KB. And no, it&#8217;s not just the smaller plans, it happens with the big boys as well:</p>
<p><a title="Nordstrom" href="http://shop.nordstrom.com/" target="_blank">http://shop.nordstrom.com/</a></p>
<p>Run a Firebug NET session on that site and you&#8217;ll see what we&#8217;re about to cover below. They use a minified but not gzipped version of jQuery (version 1.5.1), which means payload size is 51KB.</p>
<p>In that light it&#8217;s instructive to see what happens with no server size gzipping with the latest versions of each library:</p>
<p><strong>Prototype.js</strong></p>
<p><a rel="attachment wp-att-1453" href="http://www.formboss.net/blog/2011/10/jquery-vs-prototype-part-1/prototype-js-server-no-gzip/"><img class="alignnone size-full wp-image-1453" title="prototype-js-server-no-gzip" src="http://www.formboss.net/blog/wp-content/uploads/2011/10/prototype-js-server-no-gzip.png" alt="" width="796" height="140" /></a></p>
<p><strong>jQuery</strong></p>
<p><a rel="attachment wp-att-1454" href="http://www.formboss.net/blog/2011/10/jquery-vs-prototype-part-1/jquery-js-server-no-gzip/"><img class="alignnone size-full wp-image-1454" title="jquery-js-server-no-gzip" src="http://www.formboss.net/blog/wp-content/uploads/2011/10/jquery-js-server-no-gzip.png" alt="" width="796" height="140" /></a></p>
<p>Here we can can very little server time spent on the requests, but with jQuery&#8217;s minified version definitely being smaller. Again though, the 32KB shown on the jQuery website, while true as it clearly states &#8220;Gzipped&#8221;, is not what we get without the server actually gzipping, as we would expect.</p>
<p>However, as soon as we enabling server size gzipping [via Apache&#8217;s mod_deflate using:</p>
<pre class="brush: plain; title: ; notranslate">LoadModule deflate_module modules/mod_deflate.so</pre>
<p>we get:</p>
<p><strong>Prototype</strong></p>
<p><a rel="attachment wp-att-1455" href="http://www.formboss.net/blog/2011/10/jquery-vs-prototype-part-1/prototype-js-server-gzip/"><img class="alignnone size-full wp-image-1455" title="prototype-js-server-gzip" src="http://www.formboss.net/blog/wp-content/uploads/2011/10/prototype-js-server-gzip.png" alt="" width="796" height="140" /></a></p>
<p><strong>jQuery</strong></p>
<p><a rel="attachment wp-att-1456" href="http://www.formboss.net/blog/2011/10/jquery-vs-prototype-part-1/jquery-js-server-gzip/"><img class="alignnone size-full wp-image-1456" title="jquery-js-server-gzip" src="http://www.formboss.net/blog/wp-content/uploads/2011/10/jquery-js-server-gzip.png" alt="" width="796" height="140" /></a></p>
<p>The minified version of Prototype is made via <a title="JS Minifier" href="http://fmarcia.info/jsmin/test.html" target="_blank">this minifier</a>, and as we can see is essentially the same size as jQuery.</p>
<p>However, note that the non-minified version of Prototype is only ~5KB larger, and just as importantly, only take ~3 ms of extra server processing time (remember that gzipping in Apache is not free!). In other words we&#8217;re about even in that <strong>we do not need to create a minified version of Prototype</strong> and we&#8217;ll still deliver, in terms of processor load and payload size, the same thing.</p>
<h2>In Conclusion</h2>
<p>In this first post we&#8217;ve found that when properly delivered both libraries are essentially the same size. I would actually give Prototype the win however, as its smaller uncompressed size means we can simply plop the uncompressed version in to our delivery or &#8216;live&#8217; section, and then in testing, instead of nonsensical minified error messages get actual line numbers we can refer back to. True this shouldn&#8217;t happen often, (it should be our code with the error, not Prototype or jQuery), but still handy in the larger scheme.</p>
<p>In non-gzipped environments however it&#8217;s clear that jQuery gets the win. This will be important for shared hosting plans of anywhere else we do not have access to server-side gzipping.</p>
<p>It&#8217;s also noteworthy that in order for Prototype to gain some of the more advanced animation framework goodness that (I assume) jQuery already has in the base library, we&#8217;d need to add <a title="script.aculo.us" href="http://script.aculo.us/" target="_blank">Script.aculo.us</a>, which would of course make the total payload larger.</p>
<p>Those considerations aside, what&#8217;s fascinating to me is that the <em>perception </em>of jQuery being &#8220;the&#8221; light-weight library. In the past 3 years I firmly believe this has been the primary driving force behind its mass adoption and popularity. I don&#8217;t know about you but I&#8217;ve been specifically told by bosses to not include Prototype <em>because </em>of its size &#8212; but at the same time given the go-ahead for jQuery. I&#8217;ve also made similar decisions for FormBoss based on the same reasoning (<em>though not to instead use jQuery, just vanilla JavaScript</em>).</p>
<p>Now that this is no longer true for the right environments (and truth be told, this has always been the case in the right environments), I think the time&#8217;s right for Prototype to take back some of the users it rightly deserves.</p>
<p>The irony of course is back in 2008 jQuery 1.4.2 <em>was </em>in fact smaller: 3549 lines of code vs. Prototype 1.6.0.1&#8242;s 4321. But success comes with a price, and jQuery&#8217;s potential bloat can only be a good thing for users looking to &#8216;trim&#8217;. How wonderful : )</p>
<p>Please understand though: I have nothing against jQuery, I simply feel that Prototype deserves more recognition and is in many ways the superior library for some specific types of work.</p>
<p>This will only happen though, and I cannot be more serious, if the Prototype folks get off their collective butts and do the same thing as jQuery &#8211;  advertise, as prominently as you can, the fact that when minified <em>and </em>gzipped your library <strong>is the same size</strong>.</p>
<h2>Links</h2>
<p><a title="Prototype and jQuery" href="http://thinkrelevance.com/blog/2009/01/12/why-i-still-prefer-prototype-to-jquery.html">http://thinkrelevance.com/blog/2009/01/12/why-i-still-prefer-prototype-to-jquery.html</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.formboss.net/blog/2011/10/jquery-vs-prototype-part-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Understanding and Using References In PHP</title>
		<link>http://www.formboss.net/blog/2011/09/understanding-and-using-references-in-php/</link>
		<comments>http://www.formboss.net/blog/2011/09/understanding-and-using-references-in-php/#comments</comments>
		<pubDate>Mon, 26 Sep 2011 05:52:40 +0000</pubDate>
		<dc:creator>grdinic</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://www.formboss.net/blog/?p=1392</guid>
		<description><![CDATA[References are a feature of the C family of languages, and while not all that common in PHP, can be used and are quite handy in some situations. In this post I want to cover what references are and how we can (and may not want to) use them in our PHP code. What are [...]]]></description>
			<content:encoded><![CDATA[<p>References are a feature of the C family of languages, and while not all that common in PHP, <em>can</em> be used and are quite handy in some situations. In this post I want to cover what references are and how we can (and may not want to) use them in our PHP code.</p>
<p><span id="more-1392"></span></p>
<h3>What are references?</h3>
<p>At the most simple level a reference acts like a pointer (a memory address) of a variable in memory. To understand what this means a short example is in order. Let&#8217;s take this block of code:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php

  $test = 1;

  function noReference($value){

    $value = 2;

  }

  noReference($test);

  echo $test; // 1

?&gt;
</pre>
<p>Now compare with a reference-using version:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php

  $test = 1;

  function usingReference(&amp;$value){

    $value = 2;

  }

  usingReference($test);

  echo $test; // 2

?&gt;
</pre>
<p>If we run both functions on the same page the output will be:</p>
<p><strong>1 Now compare with a reference using version: 2</strong></p>
<p>Note the only difference between the two versions is the addition of the ampersand to the function parameter <strong>$value</strong>.</p>
<p>The ampersand is the <strong>reference operator</strong>, and its effect is to tell the function, in English:</p>
<p>&#8220;<em>Do not create a local copy of this parameter, use the one I&#8217;m giving to you and make any and all changes to that guy.</em>&#8221;</p>
<p>In other words, when <em>not </em>using a reference passing a parameter to a function means creating a local copy of that parameter, with any action taking place on that copy instead of the original item/value passed in. That&#8217;s why in the first code item (noReference), setting <strong>$test = 2</strong> had no effect on the variable <em>outside </em>of the function call.</p>
<h3>So why use references?</h3>
<p>As mentioned above references are an integral part of C languages, and this is for two good reasons, among others: <em>performance </em>and <em>function return limitations</em>.</p>
<p>Performance because if you think about it, making a copy of a local variable takes time and uses more space when compared to just changing the original. References can thus be handy in situations where performance is key.</p>
<p>The reason why is In C using a reference means the compiler skips that item for inclusion in the activation record (e.g., the stack). For simple data types like ints and chars this doesn&#8217;t make a huge difference, but may if passing large arrays, objects, and structures, or if passing lots of variables such that the activation record grows very large (and hence the offsets needed to access the activation record items grows).</p>
<p>Thing is, In PHP all variables (generally speaking), become zvals* which are themselves pointers to items in a hash table. Thus, the performance gains from using references will be a touch less impaction. but the gains are real in some cases, though not all as we&#8217;ll see shortly.</p>
<p>As a quick test I ran the following code in command line php (CLI) using the Linux command of: <strong>time php test.php</strong>:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php

function noRef($v){
	$v = 2;
}

function ref(&amp;$v){
	$v = 2;
}

$test = 0;

for($i = 0; $i &lt; 1000000; $i++){

	//noRef($test);
	ref($test);

}

?&gt;
</pre>
<p>The results:</p>
<p>No References:<br />
<strong>0.461</strong></p>
<p>References:<br />
<strong>0.362</strong></p>
<p>So a difference for sure, though truth be told, not a big one. This is explained by the fact that standard variables are small to begin with, the 32-bits to hold an int is the same as the 32-bits needed to hold that items address. In fact, references add an extra step of indirection to the process, in theory.</p>
<p>Again though, as PHP wraps all variables into zvals* the standard C theory on references doesn&#8217;t hold. This becomes abundantly clear when we change our code to:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php

function noRef($v){
	$v = 2;
}

function ref(&amp;$v){
	$v[7] = 2;
}

$test = range(1,100000);

for($i = 0; $i &lt; 1000000; $i++){

	noRef($test);
	//ref($test);
}

?&gt;
</pre>
<p>No References:<br />
<strong>0.517</strong></p>
<p>References:<br />
<strong>0.485</strong></p>
<p>Now we&#8217;re passing a much larger object to our function, but the time difference when running the code has been mostly erased. This is understood in terms of all variables are basically references in PHP to start with (when it comes to accessing them as we always need to use indirection to access their values), so using them will not bring any appreciable speedups for larger objects.</p>
<p>In fact, when using objects references are actually <em>slower</em>. So this test code:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php

class tester{

	private $test;

	public function setValue($value){
		$test = $value;
	}
}

function noRef($testObject, $value){
	$testObject-&gt;setValue($value);
}

function ref(&amp;$testObject, &amp;$value){
	$testObject-&gt;setValue($value);
}

$testObject = new tester();
$value = 2;

for($i = 0; $i &lt; 1000000; $i++){

	//noRef($testObject, $value);
	ref($testObject, $value);
}

?&gt;
</pre>
<p>Produces:</p>
<p>No References:<br />
<strong>0.940</strong></p>
<p>References:<br />
<strong>1.25</strong></p>
<p>Performance considerations aside, the second reason we use references comes form the fact that in C functions are limited to one return value. This means if we wish to write code that affects a longer lasting value that what&#8217;s possible in function scope, passing references is a handy way of doing so. Again though this is not really an issue for most users, as we can always return arrays/hashes that contain all the values we need. This goes for PHP and C of course.</p>
<h3>Conclusions</h3>
<p>The simple fact is references, while nice to have, are simply not a feature most of us need or will in fact want to use. As many PHP developers will not be versed in the use of references, including them in your own code can actually make portability and maintainability an issue.</p>
<p>I personally never use references if I can avoid it, in the 30,000+ lines of FormBoss codebase I use exactly <em>one</em> reference, and only because it was the most elegant solution for that particular task. I could have gotten away with not using a reference however, and perhaps I should have.</p>
<p>Perhaps the best way to put it is for raw variables like int and floats it makes sense to use references from a performance standpoint, though only if you&#8217;re sure they wont throw off other who may want to contribute to your code. For larger object types I would avoid references if possible.</p>
<h3>Links</h3>
<p>http://php.net/manual/en/language.references.pass.php</p>
]]></content:encoded>
			<wfw:commentRss>http://www.formboss.net/blog/2011/09/understanding-and-using-references-in-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating A PHP Extension</title>
		<link>http://www.formboss.net/blog/2011/07/creating-a-php-extension/</link>
		<comments>http://www.formboss.net/blog/2011/07/creating-a-php-extension/#comments</comments>
		<pubDate>Sun, 10 Jul 2011 22:39:49 +0000</pubDate>
		<dc:creator>grdinic</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[Extensions]]></category>
		<category><![CDATA[ext_skel]]></category>
		<category><![CDATA[PHP Extenions]]></category>

		<guid isPermaLink="false">http://www.formboss.net/blog/?p=1301</guid>
		<description><![CDATA[&#8220;Stock&#8221; PHP has a large number of extensions that cover just about every web-development task you can imagine. From file and FTP operations to database communication, chances are PHP already has you covered. Their is one area where PHP falls flat however, and that&#8217;s intensive data processing. As PHP internally stores all user-space variables in [...]]]></description>
			<content:encoded><![CDATA[<p>&#8220;Stock&#8221; PHP has a large number of extensions that cover just about every web-development task you can imagine. From file and FTP operations to database communication, chances are PHP already has you covered.</p>
<p>Their is one area where PHP falls flat however, and that&#8217;s intensive data processing. As PHP internally stores all user-space variables in a hash-table, algorithms that require heavy manipulation and lookups of these items will <em>always</em> be slow.</p>
<p>Of course PHP will also fall flat for us if we need some capabilities that no extension provides.</p>
<p>In this post we&#8217;ll learn about the solution to both of these issues: building custom PHP extensions. The reason why this post even exists is because of an excellent PHP tool called: <em>ext_skel</em>, as with it we can quickly create our own PHP extensions that would otherwise take many laborious hours of trial and error.</p>
<p><span id="more-1301"></span></p>
<h2>ext_skel</h2>
<p>So what&#8217;s ext_skel? ext_skel is a tool located in a source download of PHP (<a title="PHP Snaps" href="http://snaps.php.net/" target="_blank">snaps</a> or <a title="PHP Downloads" href="http://php.net/downloads.php" target="_blank">regular downloads</a>). Its job is to create the basic skeleton a PHP extension needs to run. As this post will show, provided we supply a header file with function definitions, for basic tasks ext_skel will create an almost complete project. This is a good thing as the single greatest barrier when trying to create our first extension is knowing the rather complex layout of the needed files.</p>
<h2>Setup &amp; Build Environment</h2>
<p>Before we can get started we&#8217;ll need PHP sources (<a title="PHP Snaps" href="http://snaps.php.net/" target="_blank">snaps</a> or <a title="PHP Downloads" href="http://php.net/downloads.php" target="_blank">regular downloads</a>).</p>
<p>We&#8217;ll also need GCC, which can be had on the command line with:</p>
<p>Fedora</p>
<pre>yum install gcc</pre>
<p>Ubuntu</p>
<pre>apt-get install gcc</pre>
<p>We also need a program called <strong>autoconf</strong>, which while supplied with most distributions, is for the most recent Fedora and Ubuntu <em>too</em> new.</p>
<p>Thus, we need to grab an older version from:</p>
<p><a title="GNU Software - autoconf" href="http://ftp.gnu.org/gnu/autoconf/" target="_blank">http://ftp.gnu.org/gnu/autoconf/</a></p>
<p>Look for the file:</p>
<pre>autoconf-2.13.tar.gz</pre>
<p>To avoid overwriting any existing installation of autoconf we&#8217;ll use a prefix to install this guy to a custom location, then export an environment variable to tell PHP where to find it.</p>
<p>Before we do that though, let&#8217;s create a common build environment.</p>
<p>On my Fedora 15 instance I have a folder called:</p>
<pre>/home/matthew/Documents/server</pre>
<p>Which is the master location for our work environment. Any sources for items, including the PHP and autoconf downloads, are placed in:</p>
<pre>/home/matthew/Documents/server/src</pre>
<p>When we build our software we install the results once level up using the ./configure PREFIX command, back in:</p>
<pre>/home/matthew/Documents/server</pre>
<p>Visually then, we have the source folder which contains the PHP and autoconf sources:</p>
<p><a rel="attachment wp-att-1302" href="http://www.formboss.net/blog/2011/07/creating-a-php-extension/src-directory/"><img class="alignnone size-full wp-image-1302" title="src-directory" src="http://www.formboss.net/blog/wp-content/uploads/2011/07/src-directory.png" alt="" width="708" height="434" /></a></p>
<p>And once level up from that, the location where all compiled results will be saved too:</p>
<p><a rel="attachment wp-att-1305" href="http://www.formboss.net/blog/2011/07/creating-a-php-extension/compiled-apps/"><img class="alignnone size-full wp-image-1305" title="compiled-apps" src="http://www.formboss.net/blog/wp-content/uploads/2011/07/compiled-apps.png" alt="" width="708" height="434" /></a></p>
<p>If you haven&#8217;t used the common <strong>./configure</strong> : <strong>make</strong> : <strong>make install</strong> chain before, let&#8217;s use our freshly downloaded autoconf as an example.</p>
<p>Open a terminal and navigate to the directory where the autoconf source is:</p>
<p><a rel="attachment wp-att-1306" href="http://www.formboss.net/blog/2011/07/creating-a-php-extension/cd-autoconf/"><img class="alignnone size-full wp-image-1306" title="cd-autoconf" src="http://www.formboss.net/blog/wp-content/uploads/2011/07/cd-autoconf.png" alt="" width="656" height="389" /></a></p>
<p>The key here is we need to tell the configure step where we want the final output placed. We do so by including the argument: <strong>&#8211;prefix</strong> as in:</p>
<pre>./configure --prefix=/home/matthew/Documents/server/autoconf</pre>
<p>Of course your path will be different in terms of user name (where mine says <em>matthew</em>), but so long as we get that path right, we can issue, in order:</p>
<pre>./configure --prefix=/home/matthew/Documents/server/autoconf</pre>
<pre>make</pre>
<pre>make install</pre>
<p>This will, as you can check for yourself, install the autoconf binaries in:</p>
<pre>/home/matthew/Documents/server/autoconf</pre>
<p>That&#8217;s all there is too it.</p>
<p>While we&#8217;re at it, we also need to compile PHP.</p>
<p>PHP compiles with almost the same ease, but to make sure extension building goes as smoothly as possible, we need a few more options defined.</p>
<p>For my instance, and yours as well, cd to the PHP source directory we downloaded previously and issue:</p>
<pre class="brush: plain; title: ; notranslate">
./configure --enable-debug --enable-cli --disable-xml --without-mysql --disable-sqlite --disable-cgi --disable-pear --prefix=/home/matthew/Documents/server/php-snap
</pre>
<p>The important part, again, is the &#8211;prefix path. Make sure to change yours to match your user name. To that end you&#8217;ll notice my path is:</p>
<pre>/home/matthew/Documents/server/php-snap</pre>
<p>I&#8217;ll be using this path in the code examples below, and as you may suspect, the <em>snap </em>comes from the fact that I&#8217;ve downloaded a PHP snapshot. Non-snapshot downloads should work just as well, though please note I had an issue with running ./buildconf on the non-snaps version. This may sound like nonsense right now, so if you&#8217;re interested in getting up and running as quickly as possible, I would suggest downloading the snaps version to match my environment exactly.</p>
<p>Just as before, after running the configure command issue <strong>make</strong>, and <strong>make install</strong>.</p>
<p>The final result is we now have a folder that should have the full PHP installation:</p>
<p><a rel="attachment wp-att-1309" href="http://www.formboss.net/blog/2011/07/creating-a-php-extension/screenshot-php-snap/"><img class="alignnone size-full wp-image-1309" title="Screenshot-php-snap" src="http://www.formboss.net/blog/wp-content/uploads/2011/07/Screenshot-php-snap.png" alt="" width="708" height="434" /></a></p>
<p>As the final step, we need to issue a shell command to tell the PHP build process where autoconf is. Again, this is necessary because the autoconf version we&#8217;ll have in the most recent distributions like Fedora 15 and Ubuntu 11.04 is too new for PHP. The command is simple however, and looks like:</p>
<pre>export PHP_AUTOCONF=/home/matthew/Documents/server/autoconf/bin/autoconf</pre>
<p>As always, please be sure to change the path to match your actual file system.</p>
<p>We can  check to see if this path took by running:</p>
<pre>env</pre>
<p><a rel="attachment wp-att-1310" href="http://www.formboss.net/blog/2011/07/creating-a-php-extension/running-env/"><img class="alignnone size-full wp-image-1310" title="running-env" src="http://www.formboss.net/blog/wp-content/uploads/2011/07/running-env.png" alt="" width="656" height="389" /></a></p>
<p>With all of that done we should be ready to start building our extension!</p>
<h2>Creating A Header File</h2>
<p>As mentioned in the introduction, ext_skel is an incredibly handy tool for many reasons, but my favorite is that if we supply a .h header file ext_skel will go ahead and create all of the most common glue code a c function needs to run in the PHP userspace.</p>
<p>This is, again, a good thing, as you&#8217;re probably not going to guess that a function call for a PHP extension may start with:</p>
<pre class="brush: plain; title: ; notranslate">

int argc = ZEND_NUM_ARGS();
long n;

if (zend_parse_parameters(argc TSRMLS_CC, &quot;l&quot;, n) == FAILURE) // ampersand before n omitted because of WordPress

return;
</pre>
<p><em>Of course it needs to be said if we&#8217;re truly serious about PHP extension development we&#8217;ll need to learn this stuff regardless, and more importantly, our example today is simple in that we&#8217;re only going to deal with simple parameters and returns. Anything more complex will require that we truly dive in and learn the down and dirty syntax ext_skel is kindly creating for us.</em></p>
<p>Regardless, we want to make sure we pass the <em>ext_skel</em> program a parameter which is the location of a very simple .h file.</p>
<p>The file, called <strong>fannkuch.h</strong>, has one line:</p>
<pre>int fannkuch(int n)</pre>
<p>This is a typical C method signature, and is all <em>ext_skel</em> needs to create our function code for a PHP extension. Thus, create this file on your desktop, Documents folder, or wherever you like &#8212; we need it for the next step.</p>
<h2>Running ext_skel</h2>
<p>So at this point we have a PHP installation and source directory, autoconf built and installed, a environment variable set, and a .h file with a simple method signature.</p>
<p>The next steps come down, basically, to us running a few simple commands to build our extension and compile it into the PHP core. Thus, it&#8217;s of utmost importance that we know where we should be at all times.</p>
<p>For the first step then, we need to navigate to our snaps download <strong>ext</strong> directory:</p>
<pre>cd /home/matthew/Documents/server/src/php5.3-201107100630/ext/</pre>
<p>Again, your path will different, and in this case both in name <em>and</em> PHP version number.</p>
<p>Once in the ext directory we&#8217;ll issue the magic command:</p>
<pre>./ext_skel --extname=fannkuch  --proto=/home/matthew/Desktop/fannkuch.h</pre>
<p>This command does several things. First, it creates a folder in our ext directory called <em>fannkuch</em>. The <em>&#8211;proto</em> bit is where we point to our .h file, created previously. Taking that file then, it creates several files in the newly created fannkuch directory, everything in fact, for a working extension&#8230;almost.</p>
<p>As you&#8217;ll notice after running the previous command, <em>ext_skel</em> was nice enough to print some instructions for us:</p>
<p><a rel="attachment wp-att-1317" href="http://www.formboss.net/blog/2011/07/creating-a-php-extension/next-steps/"><img class="alignnone size-full wp-image-1317" title="next-steps" src="http://www.formboss.net/blog/wp-content/uploads/2011/07/next-steps.png" alt="" width="656" height="389" /></a></p>
<p>The key here is we need to integrate our new extension into PHP. As it stands this will not happen until we edit the config.m4 file (the # 2 step above), also created by <em>ext_skel</em>:</p>
<p><a rel="attachment wp-att-1318" href="http://www.formboss.net/blog/2011/07/creating-a-php-extension/config-m4a/"><img class="alignnone size-full wp-image-1318" title="config-m4a" src="http://www.formboss.net/blog/wp-content/uploads/2011/07/config-m4a.png" alt="" width="708" height="434" /></a></p>
<h2>Editing config.m4</h2>
<p>So what changes need to be made? The config.m4 file, a little too long to be shown here, is used by the main PHP build process. Specifically, as PHP is being built via ./configure it checks all directories in the ext directory resolved by the ./buildconf step (which we&#8217;ll do shortly, and is also, you&#8217;ll notice, step 3 on the list). If a match is found it attempts to parse the m4 file and uses it to produce the final build file, which is in turn how the extension is actually compiled.</p>
<p><em>ext_skel</em> cannot, for what it&#8217;s worth, do <em>all</em> of the work for us, simply because in the world of PHP extensions their are so many variables: threaded or not, module or shared object, external dependencies or not, and so on.</p>
<p>Thus, the m4 file created by <em>ext_skel</em> contains all of the code we need to produce a working extension, it just comments most of it out and lets us decide what to expose to ./buildconf.</p>
<p>The good news is the changes we need to make are quite minimal. In fact, we just need to uncomment three lines.</p>
<p>At the top of the file we start with:</p>
<p><a rel="attachment wp-att-1321" href="http://www.formboss.net/blog/2011/07/creating-a-php-extension/m4a-start-top/"><img class="alignnone size-full wp-image-1321" title="m4a-start-top" src="http://www.formboss.net/blog/wp-content/uploads/2011/07/m4a-start-top.png" alt="" width="588" height="463" /></a></p>
<p>Uncomment lines 16 and 18 for:</p>
<p><a rel="attachment wp-att-1322" href="http://www.formboss.net/blog/2011/07/creating-a-php-extension/m4-finish-top/"><img class="alignnone size-full wp-image-1322" title="m4-finish-top" src="http://www.formboss.net/blog/wp-content/uploads/2011/07/m4-finish-top.png" alt="" width="588" height="463" /></a></p>
<p>Then, at the bottom of the file we need to uncomment just one line:</p>
<p><a rel="attachment wp-att-1323" href="http://www.formboss.net/blog/2011/07/creating-a-php-extension/m4-bottom-start/"><img class="alignnone size-full wp-image-1323" title="m4-bottom-start" src="http://www.formboss.net/blog/wp-content/uploads/2011/07/m4-bottom-start.png" alt="" width="588" height="463" /></a></p>
<p>Line 60 becomes:</p>
<p><a rel="attachment wp-att-1324" href="http://www.formboss.net/blog/2011/07/creating-a-php-extension/m4-bottom-finish/"><img class="alignnone size-full wp-image-1324" title="m4-bottom-finish" src="http://www.formboss.net/blog/wp-content/uploads/2011/07/m4-bottom-finish.png" alt="" width="588" height="463" /></a></p>
<p>Make sure to save the file when done&#8211;we&#8217;re almost ready to get our first extension up and running.</p>
<h2>Building Our Extension</h2>
<p>Right&#8211;so now we have a properly configured m4 file, one that will be picked up by ./buildconf in this next step, read, and then presented to the ./configure step.</p>
<p>First, we need to bounce up one directory so that we&#8217;re in the main PHP source directory, e.g.:</p>
<pre>/home/matthew/Documents/server/src/php5.3-201107100630</pre>
<p>This is the big one. Provided we&#8217;re installed autoconf and supplied the proper PHP_AUTOCONF environment variable, we should be able to run:</p>
<pre>./buildconf</pre>
<p>If all goes well the command line will spit out a few lines of warnings and notices&#8211;none of these are an issue.</p>
<p><em>If not, and this was eluded to earlier, I also had issues with &#8216;production&#8217; versions of PHP not taking too kindly to ./buildconf. Their is a &#8211;force flag that can be set which should override these issues, though I did not have any luck with that either. At this point, as we&#8217;re just getting started, it is well worth using a debug (snaps) version of PHP, as it&#8217;s much easier to debug anyway.</em></p>
<p><strong>One other quick point:</strong> running ./buildconf is what processes <strong>any and all</strong> directives we&#8217;ve set in the extensions config.m4 file. Thus, if we change the config.m4 file, we <strong>must</strong> rerun ./buildconf!</p>
<p>Provided the previous ./buildconf step worked, we can now instruct the PHP build process to include our new extension with:</p>
<pre>./configure --enable-fannkuch -prefix=/home/matthew/Documents/server/php-snap</pre>
<p>Note that we&#8217;re saying &#8211;enable-fannkuch: The use of <em>&#8211;enable</em> as opposed to &#8211;<em>with</em> means the extension doesn&#8217;t have any external dependencies.</p>
<p>The prefix bit, like it has been in all cases, means that we have PHP installed to a custom location, and that&#8217;s where all files need to be delivered when we run <em>make install</em>. Thus, it should be said that the directory we&#8217;re in right now is just the source code version of our extension, when we run <em>make</em> <em>install </em>we&#8217;re sending our extension to the php-snap folder. Yes, it&#8217;s a real, official extension we&#8217;re building here: )</p>
<p>Finally, we now need to run:</p>
<pre>make</pre>
<pre>make install</pre>
<h2>Running The Extension</h2>
<p>At this point we&#8217;re ready to try out our new extension.</p>
<p>As you may have noticed in step 6 after running <em>ext_skel</em>, we can simply run:</p>
<pre>../../php-snap/bin/php ext/fannkuch/fannkuch.php</pre>
<p>That is, we bounce up two directories to hit our actual php binary, then dive into the ext/fannkuch directory to run the test file <em>ext_skel</em> was nice enough to create for us.</p>
<p>If all goes well we&#8217;ll see:</p>
<p><a rel="attachment wp-att-1325" href="http://www.formboss.net/blog/2011/07/creating-a-php-extension/success/"><img class="alignnone size-full wp-image-1325" title="success" src="http://www.formboss.net/blog/wp-content/uploads/2011/07/success.png" alt="" width="656" height="389" /></a></p>
<p>At this point we can also test the actual function call we defined, <em>fannkuch(int)</em>.</p>
<p>To do so I created a new file called <strong>test.php</strong> in the raw extension source folder:</p>
<p><a rel="attachment wp-att-1328" href="http://www.formboss.net/blog/2011/07/creating-a-php-extension/test-file/"><img class="alignnone size-full wp-image-1328" title="test-file" src="http://www.formboss.net/blog/wp-content/uploads/2011/07/test-file.png" alt="" width="708" height="434" /></a></p>
<p>&#8230;with the following contents:</p>
<pre>&lt;?php
 echo fannkuch(10);
?&gt;</pre>
<p>We can now call this guy with:</p>
<pre>../../php-snap/bin/php ext/fannkuch/test.php</pre>
<p>To which we&#8217;ll get:</p>
<p><em>Warning: fannkuch: not yet implemented in /home/matthew/Documents/server/src/php5.3-201107100630/ext/fannkuch/test.php on line 2</em></p>
<p>That&#8217;s no fun, but fear not, as next we&#8217;ll add to this extension to do something interesting.</p>
<h2>Adding To The Extension</h2>
<p>A PHP extension is far more interesting when it does something useful. While we&#8217;re not going to get too complex here, we will implement a function that accepts a parameter and returns a value.</p>
<p>To do so we need to modify the part of the <strong>fannkuch.c</strong> file <em>ext_skel</em> created for us which defines the userspace PHP function, <em>fannkuch()</em>.</p>
<p>The good news is <em>ext_skel</em> has done just about all of the hard work for us. By hard work I mean creating PHP extensions from scratch means learning a whole lot of C Macros and Zend calling conventions, and if you&#8217;re like me, limitations of C as opposed to C++.</p>
<p>The first step then is to open our<strong> fannkuch.c</strong> file and scroll down to the line:</p>
<pre>PHP_FUNCTION(fannkuch)</pre>
<p>This macro, again, created for us by <em>ext_skel</em>, is how user-space functions are defined by PHP. That is, in a PHP source file, provided this extension has been loaded, I can call <em>fannkuch()</em> and our extension function will be called. As you&#8217;ll notice, the error/warning we got when runnng test.php comes from the default implementation thereof:</p>
<pre>PHP_FUNCTION(fannkuch)
{
 int argc = ZEND_NUM_ARGS();
 long n;

 if (zend_parse_parameters(argc TSRMLS_CC, "l", &amp;n) == FAILURE)
 return;

 php_error(E_WARNING, "fannkuch: not yet implemented");
}
/* }}} */</pre>
<p>Thus, to &#8220;do something interesting&#8221; means we need to remove that <em>php_error</em> line and implement our own C code.</p>
<h3>Custom Code Implementation</h3>
<p>Again, we&#8217;re not going to get too deep here, but implementing code is only possible if we know a few important points about PHP extension writing. Most important of these topics for us: input parameters and returning values.</p>
<h4>Input Parameters</h4>
<p>Passing parameters in Zend extensions is a large topic as you would expect, but once again <em>ext_skel</em> comes through by defining <em>long n</em> for us. Of course as programmers it&#8217;s odd to call and define a function where we don&#8217;t pass parameters directly, but with a heavy helping of macros like <em>zend_parse_parameters</em> that&#8217;s exactly what happens.</p>
<p>That is, in our original <em>fannkuch.h</em> file we defined our function as:</p>
<pre>int fannkuch(int n)</pre>
<p><em>ext_skel</em> thus went in and said: right, we need a parameter called <em>n</em>, I&#8217;ll create one for us and also add the code to implement the actual variable assignment:</p>
<pre>if (zend_parse_parameters(argc TSRMLS_CC, "l", &amp;n) == FAILURE)
 return;</pre>
<p>This macro grabs the passed value from the internal parameter stack and make it available to our function via the <em>n</em> parameter. To add more parameters to this function we would need to add more entries to the <em>zend_parse_parameters</em> macro, which is unfortunately outside of the scope of this post.</p>
<h4>Returning Values</h4>
<p>Just like input parameters, returning values in PHP extensions is unique. Whereas in C we can use a simple return statement, in PHP extensions we once again implement macros. Different versions exist for the type of variable we return, but in the case of our function, we&#8217;ll return a long with:</p>
<pre>RETVAL_LONG()
return;</pre>
<p>In other words, in PHP extensions we need to push any return values into a larger hash table structure, which is then, at function termination, possibly accessed via other structures and functions in the larger context of the core PHP Zend engine (as in our example, we need to access the return value of our function for the echo call) .</p>
<p>Critically, we still need to terminate our function which means we <em>still</em> issue a return as normal (<em>we can however, use the RETURN_LONG() macro to do both</em>).</p>
<p>Coincidentally, this is also why PHP is so darn slow for intensive data processing where user space code dictates the parameter space. It&#8217;s also, of course, why such tasks benefit so greatly from custom extensions. If we have code that requires many variable accesses of any sort, moving such code into an extension and only passing a few parameters provides positively <em>massive</em> gains, as we&#8217;ll see shortly.</p>
<h4>The Code</h4>
<p>So the code that&#8217;s we use as a test extension is none other than our Sunspider fannkuch test code.</p>
<p>I&#8217;ve added a few comments along the way with some important points, such as how we cannot use <em>bool</em> as a type but rather <em>zend_bool</em>, and how we cannot declare for() loop variables inline.</p>
<p>In all these are minor changes, and most importantly, after a few hiccups of learning Zend syntax for how parameters and returns work, this code, originally JavaScript, then C++, and now C, was almost a copy/paste affair.</p>
<pre class="brush: cpp; first-line: 1; pad-line-numbers: false; title: ; notranslate">
PHP_FUNCTION(fannkuch)
{
    int argc = ZEND_NUM_ARGS();
    long n;

    if (zend_parse_parameters(argc TSRMLS_CC, &quot;l&quot;, &amp;n) == FAILURE)
        return;

    //php_error(E_WARNING, &quot;fannkuch: not yet implemented&quot;);

    // my code
    int check = 0;
    int perm[n];
    int perm1[n];
    int count[n];
    int maxPerm[n];
    int maxFlipsCount = 0;
    int m = n - 1;

    // cannot declare loop values in non-c99 mode
    int i;
    for (i = 0; i &lt; n; i++){
        perm1[i] = i;
    }

    int r = n;

    zend_bool t = 1; // zend/c cannot use bool, but zend_bool
    while (1) { // no matter, just use 1 until return

        // write-out the first 30 permutations
        if (check &lt; 30){
            int s = 0;
            int i;
            for(i=0; i&lt;n; i++) s += (perm1[i]+1);
            check++;
        }

        while (r != 1) { count[r - 1] = r; r--; }

        if (!(perm1[0] == 0 || perm1[m] == m)) {
            int i;
            for (i = 0; i &lt; n; i++) perm[i] = perm1[i];
            int flipsCount = 0;
            int k;

            while (!((k = perm[0]) == 0)) {
                int k2 = (k + 1) &gt;&gt; 1;
                int i;
                for (i = 0; i &lt; k2; i++) {
                    int temp = perm[i]; perm[i] = perm[k - i]; perm[k - i] = temp;
                }
                flipsCount++;
            }

            if (flipsCount &gt; maxFlipsCount) {
                maxFlipsCount = flipsCount;
                int i;
                for (i = 0; i &lt; n; i++) maxPerm[i] = perm1[i];
            }
        }

        zend_bool g = 1;
        while (1) {
            if (r == n) {
                // return maxFlipsCount;
                // zend return method - can also use RETURN_LONG
                RETVAL_LONG(maxFlipsCount);
                return;
            }
            int perm0 = perm1[0];
            int i = 0;

            while (i &lt; r) {
                int j = i + 1;
                perm1[i] = perm1[j];
                i = j;
            }

            perm1[r] = perm0;
            count[r] = count[r] - 1;

            if (count[r] &gt; 0) break;
            r++;
        }
    }

    // my code end

}
</pre>
<p>How do we test the updated extension code? Simple: save the .c file and, back in the command line, which should still point to:</p>
<pre>/home/matthew/Documents/server/src/php5.3-201107100630</pre>
<p>We need only run:</p>
<pre>make</pre>
<p>and:</p>
<pre>make install</pre>
<p>This will completely rebuild our extension with the new code, which we can then instantly try out via our previous command to the test file:</p>
<pre>../../php-snap/bin/php ext/fannkuch/test.php</pre>
<p>If all went well, we should now get the result of our <em>fannkuch()</em> call, which should be 38.</p>
<h2>Closing Remarks &amp; Performance</h2>
<p>Building more complex PHP extensions is not exactly an easy affair, as here we&#8217;ve only scratched the surface. Their are resource types, hashes, reference type variables, Objects, on and on&#8230;the key though, is by utilizing the excellent <em>ext_skel</em> tool we get our first extension up and running very quickly. We can then, provided we&#8217;ve given <em>ext_skel</em> a header file to work with, even implement our own code with very little effort. In many cases this may be all that&#8217;s required&#8211;just a simple addition to protect your code-base, add needed functionality, and so on.</p>
<p>PHP, from the user <em>or</em> developer space, never ceases to surprise and delight me.</p>
<p>Of course as a final point it should be said that implementing fannkuch as an extension is, by no exaggeration, simply stunning in terms of raw performance when compared to standard PHP.</p>
<p>From a few quick tests via:</p>
<pre>time ../../php-snap/bin/php ext/fannkuch/test.php</pre>
<p>Show that where:</p>
<p>n = 9:</p>
<pre>30
real	0m0.025s
user	0m0.018s
sys	0m0.006s</pre>
<p>n = 10</p>
<pre>38
real	0m0.189s
user	0m0.187s
sys	0m0.001s</pre>
<p>n = 11</p>
<pre>51
real	0m2.246s
user	0m2.239s
sys	0m0.003s</pre>
<p>Compare that to fully optimized C++<br />
n = 9</p>
<pre>0m0.019s</pre>
<p>n = 10</p>
<pre>0m0.188s</pre>
<p>n = 11</p>
<pre>0m2.261s</pre>
<p>And vanilla PHP:<br />
n = 9</p>
<pre>0m1.624s</pre>
<p>n = 10</p>
<pre>0m19.058s</pre>
<p>n = 11</p>
<pre>> 4 minutes</pre>
<p>In short: It&#8217;s as fast as C++, and simply destroys vanilla PHP.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.formboss.net/blog/2011/07/creating-a-php-extension/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Benchmarks: JavaScript vs. PHP vs. HPHP vs C++</title>
		<link>http://www.formboss.net/blog/2011/07/benchmarks-javascript-vs-php-vs-hphp-vs-c/</link>
		<comments>http://www.formboss.net/blog/2011/07/benchmarks-javascript-vs-php-vs-hphp-vs-c/#comments</comments>
		<pubDate>Wed, 06 Jul 2011 20:04:01 +0000</pubDate>
		<dc:creator>grdinic</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Linux/Web Servers]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://www.formboss.net/blog/?p=1228</guid>
		<description><![CDATA[Just a quick spattering of some benchmarks I ran while testing a program I&#8217;m developing internally. The first three are of the fannkuch benchmark found on the sunspider test site, only ported over to C++ and PHP in addition to the JS version. The browser used for all tests was Firefox 5. The HPHP listing [...]]]></description>
			<content:encoded><![CDATA[<p>Just a quick spattering of some benchmarks I ran while testing a program I&#8217;m developing internally.</p>
<p>The first three are of the <a title="Sunspider Benchmark" href="http://www.webkit.org/perf/sunspider-0.9/access-fannkuch.html" target="_blank">fannkuch benchmark found on the sunspider test site</a>, only ported over to C++ and PHP in addition to the JS version. The browser used for all tests was Firefox 5.</p>
<p>The HPHP listing is a compiled <a title="Hip Hop PHP" href="https://github.com/facebook/hiphop-php/wiki/" target="_blank">Hip Hop PHP</a> version, which is interesting as it shows the relative difference between it and vanilla PHP.</p>
<p>The last item, Benchmark.php, is the same benchmark file you&#8217;ll find in a <a title="PHP Source" href="http://www.php.net/downloads.php" target="_blank">PHP source download</a>.</p>
<p>See the full benchmarks after the jump!</p>
<p><span id="more-1228"></span></p>
<p><strong>access-fannkuch &#8211; n=9</strong></p>
<p>JavaScript: 0.204</p>
<p>PHP: 1.624</p>
<p>HPHP: 0.538</p>
<p>C++ .20</p>
<p><strong>access-fannkuch &#8211; n=10</strong></p>
<p>JavaScript: 3.062</p>
<p>PHP: 19.058</p>
<p>HPHP: 6.395</p>
<p>C++ .189</p>
<p><strong>access-fannkuch &#8211; n=11</strong></p>
<p>JavaScript: 40.297</p>
<p>PHP: ~4 minutes</p>
<p>HPHP: 23.713</p>
<p>C++ 2.265</p>
<p><strong>Benchmark.php</strong></p>
<p>PHP: 2.542</p>
<p>HPHP: 0.547</p>
]]></content:encoded>
			<wfw:commentRss>http://www.formboss.net/blog/2011/07/benchmarks-javascript-vs-php-vs-hphp-vs-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Testing JavaScript In Modern Browsers</title>
		<link>http://www.formboss.net/blog/2011/06/testing-javascript-in-modern-browsers/</link>
		<comments>http://www.formboss.net/blog/2011/06/testing-javascript-in-modern-browsers/#comments</comments>
		<pubDate>Sat, 04 Jun 2011 17:33:00 +0000</pubDate>
		<dc:creator>grdinic</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://www.formboss.net/blog/?p=1222</guid>
		<description><![CDATA[I recently installed Internet Explorer 9, and while the browsers interface seems nice, the JavaScript performance in terms of running FormBoss leaves something to be desired: In short, it&#8217;s completely unusable. This was not at all the case in IE 8, and when you consider IE 9 was supposed to be the release that finally [...]]]></description>
			<content:encoded><![CDATA[<p>I recently installed Internet Explorer 9, and while the browsers interface seems nice, the JavaScript performance in terms of running FormBoss leaves something to be desired: In short, it&#8217;s completely unusable.</p>
<p>This was not at all the case in IE 8, and when you consider IE 9 was supposed to be the release that finally fixed JavaScript this is quite disheartening.</p>
<p>As any serious JavaScript programmer can attest to, the irony of IE has always been that in many ways its been more &#8216;correct&#8217; in terms of standards than the other browsers. That is, what passes in Firefox in terms of JavaScript code fails in IE not because IE is wrong, but because Firefox is so forgiving (and by extension, wrong). This is doubly true when we add a JavaScript library like <a href="http://www.prototypejs.org/">Prototype JS</a> into the mix, in that the libraries attempts to smooth over browser differences may expose us to subtitle differences in core JavaScript behavior.</p>
<p>On that springs to mind is how some Prototype JS objects property counts are handled. In Firefox an object may be shown to have a length of 1, but in IE that same object had a length of 2. Another example, if memory serves, had to do with valid names of objects. IE has always been more strict in terms of using names that start with numbers, and so on.</p>
<p>Such differences can be hard to spot in production code, and almost always leads to hours of careful testing and debugging.</p>
<p>Thus, as part of my own production process I&#8217;d like to share two links that may help you determine if such issues reside in your code or the browser/library begin used.</p>
<h4>Google Labs Sputnik JavaScript Test</h4>
<p><a title="Sputnik Test" href="http://sputnik.googlelabs.com/">http://sputnik.googlelabs.com/</a></p>
<p>This test is very interesting to me as it confirms, among other things, that IE 9&#8242;s JavaScript engine is generally more &#8216;correct&#8217; in terms of standards that the competition. For example, when run in IE 9 I get 71 failed tests, whereas <a title="Chrome Canari" href="http://tools.google.com/dlpage/chromesxs">Chrome Canari</a> generates 136 and Firefox 4 181.</p>
<p>In almost all of the cases that &#8216;fail&#8217; we see the failed test is something the casual JavaScript author may easily do.</p>
<p>For example, in test s12.5_A9_T1 we check for a function declaration within an &#8216;if&#8217; statement:</p>
<pre>// Copyright 2009 the Sputnik authors.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/**
* @name: S12.5_A9_T1;
* @section: 12.5;
* @assertion: Function declaration within an "if" statement is not allowed;
* @description: Declaring function within an "if" statement;
* @negative;
*/

if (true) {
    function __func(){};
} else {
    function __func(){};
}

testCompleted();</pre>
<p>Have I ever done this? No. Could I see others or even me late at night? Sure. The point being that as you peruse some of the test that say, Firefox 4 fails, it becomes obvious that many of the failures stem from Firefox being &#8216;fast and easy&#8217; with some of the rules, which ironically, can make creating JavaScript code easier.</p>
<h4>Framework Library Test</h4>
<p><a title="Framework Test" href="http://dante.dojotoolkit.org/taskspeed/">http://dante.dojotoolkit.org/taskspeed/</a></p>
<p>This test highlights the differences in the major JavaScript libraries. Of core importance to me are the functions that manipulate the DOM, such as <em>append</em>, <em>insertbefore</em>, <em>insertafter</em>, and so on.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.formboss.net/blog/2011/06/testing-javascript-in-modern-browsers/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>XML Namespaces And XPath</title>
		<link>http://www.formboss.net/blog/2011/05/xml-namespaces-and-xpath/</link>
		<comments>http://www.formboss.net/blog/2011/05/xml-namespaces-and-xpath/#comments</comments>
		<pubDate>Sun, 15 May 2011 17:20:27 +0000</pubDate>
		<dc:creator>grdinic</dc:creator>
				<category><![CDATA[Form Creation]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[namespaces]]></category>
		<category><![CDATA[registerXPathNamespace]]></category>
		<category><![CDATA[xml namespace]]></category>
		<category><![CDATA[xpath]]></category>

		<guid isPermaLink="false">http://www.formboss.net/blog/?p=1194</guid>
		<description><![CDATA[In this post we&#8217;ll cover a topic you&#8217;ll no doubt run into when dealing with SOAP web services: parsing XML data that uses namespaces via XPath. As I&#8217;m a PHP guy this will be PHP centric in that we&#8217;ll use SimpleXML for our parsing needs. The techniques and general ideas presented herein however, are applicable [...]]]></description>
			<content:encoded><![CDATA[<p>In this post we&#8217;ll cover a topic you&#8217;ll no doubt run into when dealing with SOAP web services: parsing XML data that uses namespaces via XPath.</p>
<p>As I&#8217;m a PHP guy this will be PHP centric in that we&#8217;ll use <a href="http://php.net/manual/en/book.simplexml.php">SimpleXML</a> for our parsing needs. The techniques and general ideas presented herein however, are applicable to almost all XML/XPath processing languages.</p>
<p><span id="more-1194"></span></p>
<h2>Why XPath?</h2>
<p>When you think about an XML document it becomes apparent their are two main ways to extract data: iterative and direct (and of course a combination of the two).</p>
<p><strong>Iterative: </strong>The iterative approach makes sense when we have a series of child elements that sit under one parent node, and our processing needs demand that we have access to each child. For example, <a title="periodic.xml" href="http://www.w3.org/XML/Binary/2005/03/test-data/Over100K/periodic.xml" target="_blank">periodic.xml</a> encapsulates the Periodic Table of the Elements like so:</p>
<pre id="line1">&lt;?xml version="1.0"?&gt;
&lt;PERIODIC_TABLE&gt;
  &lt;ATOM&gt;
    &lt;NAME&gt;Actinium&lt;/NAME&gt;
    &lt;ATOMIC_WEIGHT&gt;227&lt;/ATOMIC_WEIGHT&gt;
    &lt;ATOMIC_NUMBER&gt;89&lt;/ATOMIC_NUMBER&gt;
  &lt;/ATOM&gt;
  &lt;ATOM&gt;
    &lt;NAME&gt;Aluminum&lt;/NAME&gt;
    &lt;ATOMIC_WEIGHT&gt;26.98154&lt;/ATOMIC_WEIGHT&gt;
    &lt;ATOMIC_NUMBER&gt;13&lt;/ATOMIC_NUMBER&gt;
  &lt;/ATOM&gt;
&lt;/PERIODIC_TABLE&gt;</pre>
<p>Under the root node sits many instances of ATOM, and so when parsing this file we would most likely create an internal structure that mimics this layout such that each ATOM element would be read and processed in turn.</p>
<p>In practical terms iterative processing generally comes in the form of a <strong>foreach()</strong> statement on a SimpleXML object.</p>
<p>Iterative processing keeps our parsing source code clean and concise. We would not create a separate function, for example, for each ATOM node during the parsing stage (we could <em>call </em>certain functions of course for each ATOM element as they were being processed, but not create a separate parser for each element).</p>
<p><strong>Direct:</strong> The direct approach is where XPath comes into play. <a title="XPATH" href="http://www.w3.org/TR/xpath/" target="_blank">XPath</a> is a standard for addressing parts of an XML document. <em>Addressing </em>is a broad term of course, but in the most general sense the XPath standard provides means for reaching any part of your XML document via <strong>location paths</strong>. This should make sense as an XML document, after all, is just a tree-like structure with parent/children relationships connecting said nodes.</p>
<p>Location paths play a vital roll when dealing with namespaces, the main topic of this post, so we&#8217;ll get back to these guys in just a moment.</p>
<p>Before we get to that though, the main idea is in the iterative approach we make a conscious decision to loop through an XML document or subset of a document. In the Direct (XPath) method (for our purposes), we instead want to <em>target a very specific part</em> of the XML document. This is often the case when working with web-services like SOAP where we know only 1 record (node) has been returned, which means creating a looping logical structure over a returned document would be a waste of time, as their is nothing to &#8216;loop&#8217; over.</p>
<h2>XPath In Action</h2>
<p>If you&#8217;ve never used XPath before you&#8217;re in for a treat: it&#8217;s beautifully simple to use.</p>
<p>Assume the following trivial XML data:</p>
<pre>&lt;foo&gt;
     &lt;bar&gt;
         &lt;a&gt;Stuff&lt;/a&gt;
     &lt;/bar&gt;
&lt;/foo&gt;</pre>
<p>We want to retrieve the <strong>a</strong> nodes value.</p>
<p>In <a title="XPath in SimpleXML" href="http://www.php.net/manual/en/simplexmlelement.xpath.php" target="_blank">XPath,</a> as defined in PHP&#8217;s SimpleXML, we would use the following code:</p>
<pre>$g = &lt;&lt;&lt;EOG
&lt;foo&gt;
 &lt;bar&gt;
 &lt;a&gt;Stuff&lt;/a&gt;
 &lt;/bar&gt;
&lt;/foo&gt;
EOG;

$t_xml = new SimpleXMLElement($g);

$data = $t_xml-&gt;xpath("//a");

var_dump($data);
// array(1) {   [0]=&gt;   object(SimpleXMLElement)#3 (1) {     [0]=&gt;     string(12) "Stuff"   } }</pre>
<p>That is, we create an instance of SimpleXML to which we feed in our sample XML data. At this point we have object of type SimpleXML which can have xpath() called as a member function.</p>
<p>The xpath() function call takes a string which, as described above, is the <em>location path</em> (or just <em>xpath</em>), of the node(s) we wish to find.</p>
<p>Of course knowing the XPath syntax is the important bit here, though users of REGEX should have no problem <a title="XPath Selectors" href="http://www.w3schools.com/xpath/xpath_syntax.asp" target="_blank">picking up the basics</a>.</p>
<p>In this case we&#8217;ve used //a, which means: starting from the current node (which in this case is the root node), return any child node that matches <em>a</em>.</p>
<p>As a result of this call xpath() returns a new object of type SimpleXML that has one element, the <strong>a</strong> node with the string <em>Stuff</em>.</p>
<p>Even better, if we have <em>n</em> nodes of <strong>a</strong>, then the above xpath() call would return <em>n</em> <strong>a</strong> nodes.</p>
<p>It&#8217;s fair to say that XPath is a very useful tool for XML processing. If we know the path to the element we need we can simply provide a location path and grab it strait away.</p>
<p>Of course if we have an iterative loop in mind XPath can also be a huge time-saver, as its powerful path selection syntax means we can narrow down which nodes we process in the first place.</p>
<h2>XPath and Namespaces</h2>
<p>The difficulty level changes somewhat when we add XML namespaces into the mix.</p>
<p>Namespaces in XML exist to address the problem of having two elements with the same name meaning different things. Of course it stands to reason <em>why </em>this would ever happen, and the answer is it shouldn&#8217;t if <em>you&#8217;ve</em> designed the file. The problem, thus, lies with mixing XML files and data from <em>different </em>sources (mashups, mixins, etc).</p>
<p>A possible example is a <em>layered </em>document that has embedded XML where the node <em>table </em>is defined twice. One definition is for the HTML table element, the second is for a table in the XML data structure.</p>
<p>Namespaces come to rescue by adding a <em>prefix </em>to the node name in question.</p>
<p>Thus this troubled XML:</p>
<pre>&lt;root&gt;
 &lt;data&gt;
   &lt;table&gt;
     &lt;a&gt;HTML Stuff&lt;/a&gt;
   &lt;/table&gt;
 &lt;/data&gt;
 &lt;xmlnode&gt;
   &lt;table&gt;
     &lt;a&gt;XML Stuff&lt;/a&gt;
   &lt;/table&gt;
 &lt;/xmlnode&gt;
&lt;/root&gt;</pre>
<p>Becomes:</p>
<pre>&lt;root&gt;
 &lt;html xmlns="http://www.somethign.com/html"&gt;
   &lt;table&gt;
     &lt;a&gt;HTML Stuff&lt;/a&gt;
   &lt;/table&gt;
 &lt;/html&gt;
 &lt;xmlnode xmlns="http://www.somethign.com/xml"&gt;
   &lt;table&gt;
     &lt;a&gt;XML Stuff&lt;/a&gt;
   &lt;/table&gt;
 &lt;/xmlnode&gt;
&lt;/root&gt;</pre>
<p>In the second block we&#8217;ve added what are called <em>Default Namespaces</em> to the parent nodes in the form of <em>xmlns=&#8221;[URI]&#8220;.<br />
</em></p>
<p>It&#8217;s vital to note this means the <em>entire block (all child nodes of the one defined with the namespace)</em> use the defined namespace, which means the individual child items need not be prefixed as the namespace is <em>implied</em>.</p>
<p>With their new namespaces the two <em>table </em>elements are now considered different entities and vitally, this means to an XPath query they&#8217;re different as well.</p>
<p>While this syntax is simple and elegant, we can also prefix each node individually as in:</p>
<pre>&lt;root&gt;
 &lt;h:html xmlns:h="http://www.somethign.com/html"&gt;
   &lt;h:table&gt;
     &lt;h:a&gt;Good Stuff&lt;/h:a&gt;
   &lt;/h:table&gt;
 &lt;/h:html&gt;    

 &lt;x:xmlnode xmlns:x="http://www.somethign.com/xml"&gt;
   &lt;x:table&gt;
     &lt;x:a&gt;Good Stuff 2&lt;/x:a&gt;
   &lt;/x:table&gt;
 &lt;/x:xmlnode&gt;
&lt;/root&gt;</pre>
<p>It may  help to think of this version as if we&#8217;re creating variable  assignments in a traditional programming language such as Pascal. The namespace for the child nodes is <em>defined </em>by the <strong>xmlns:[prefix]=&#8221;[URI]&#8221; </strong>block (usually in the first instance of that node, though we can also define these at the top of the document, for example), then used in the child nodes open/close block in the <strong>[prefix]:node-name</strong> manner.</p>
<p>In either version we&#8217;ve now defined each table node as different from  the other via its namespace attribute. The first version, via the  Default Namespace, is arguably easier to read, is certainly easier to  code by hand as well as being less prone to error.</p>
<p>I have to admit this is the trickiest part of the namespace plus xml syntax, and the reason is simple though subtle: as programmers we recoil when seeing a variable used before its definition. In PHP this is grounds for trouble, and in stricter languages like C++ a recipe for disaster. And yet despite this that&#8217;s <em>exactly </em>what we do in the example above.</p>
<p>To be specific, in the code from above:</p>
<pre>&lt;h:html xmlns:h="http://www.somethign.com/html"&gt;</pre>
<p>What&#8217;s we&#8217;re essentially saying is <em>h</em> is the prefix for <em>html</em>, but <em>h</em> isn&#8217;t even defined until the next code chunk. Thus, as we look at this code block and try to understand it we&#8217;re forced to read <em>ahead </em>to find the meaning of <em>h</em>.</p>
<p>In time this becomes second nature, but when learning this syntax it&#8217;s a real bear and feels quite unnatural.</p>
<p>Stylistics aside, as hinted at above it&#8217;s instructive to see what happens to our original XPath query&#8217;s against<strong> a</strong> in these new namespace versions.</p>
<p>Thus, if we run:</p>
<pre>$data = $t_xml-&gt;xpath("//a");</pre>
<p>We now get a null or empty result. Why?</p>
<p>Our result is empty because we no longer match an<strong> a</strong> node as this <em>element no longer exists</em>. What <em>does </em>exist is the namespace version of the <strong>a</strong> node, e.g.:</p>
<pre>//h:a</pre>
<p>and</p>
<pre>//x:a</pre>
<p>In other words, when using namespaces we must tell the XPath query engine <em>which </em>namespace we wish to query against.</p>
<p>Exactly <em>how </em>we do that depends on your XPath engine, but for SimpleXML we call the function:</p>
<pre>$data-&gt;registerXPathNamespace("prefix", "namespace-uri");</pre>
<p>It needs to be stressed this is the &#8216;key&#8217; to using namespaced XML with XPath. We tell the XPath engine: &#8220;This document has a namespace, this is the one I want the next query to use.&#8221;</p>
<p>The trick to this however, is that as described above we have two ways of defining the namespace for our nodes: we can use the Default Namespace method or manually add prefixes to each element. The call to registerXPathNamespace() will be the same in both cases, but in the Default Namespace method we&#8217;re creating an explicit mapping of the prefix to a xmlns URI, whereas in the manual method this link has already been created, <em><strong>but we can redefine the prefix to something else</strong></em>.</p>
<p>I realize this is confusing so let&#8217;s jump in and look at an example.</p>
<p>This code uses Default Namespaces, which means our call to registerXPathNamespace() <em>will define what the prefix is</em>. Not for the XML document mind you, but for the xpath() query we wish to run:</p>
<pre>$namespaces_default = &lt;&lt;&lt;EOG
&lt;root&gt;
 &lt;html xmlns="http://www.somethign.com/html"&gt;
 &lt;table&gt;
 &lt;a&gt;Good Stuff&lt;/a&gt;
 &lt;/table&gt;
 &lt;/html&gt;
 &lt;xmlnode xmlns="http://www.somethign.com/xml"&gt;
 &lt;table&gt;
 &lt;a&gt;Good Stuff 2&lt;/a&gt;
 &lt;/table&gt;
 &lt;/xmlnode&gt;
&lt;/root&gt;
EOG;

$t_xml = new SimpleXMLElement($namespaces_default);

$t_xml-&gt;registerXPathNamespace("x", "http://www.somethign.com/xml");

$data = $t_xml-&gt;xpath("//x:a");

var_dump($data);
// array(1) {   [0]=&gt;   object(SimpleXMLElement)#3 (1) {     [0]=&gt;     string(12) "Good Stuff 2"   } }</pre>
<p>As you can see we&#8217;ve set the prefix to x, which means our XPath path becomes: //x:a. Vitally we could just have easily used b or any other set of legal characters for the prefix. Hence, when using Default namespace syntax the XML document&#8217;s namespace, while it exists, is unnamed&#8211;it has no callable value. It&#8217;s only <em>after </em>we&#8217;ve called registerXPathNamespace() that a valid prefix mapping has come into its own and can now be queried in our xpath() function calls.</p>
<p>Critically, you&#8217;ll notice the namespace name (a URL): <strong>http://www.something.com/xml</strong>, doesn&#8217;t actually exist&#8211;it&#8217;s just an identifier. For some definitions this will exist, such as the specification for the HTML table element. But <a title="XML Namespace Specification" href="http://www.w3.org/TR/xml-names/" target="_blank">per specification</a> this simply needs to be a URI as defined by <a title="RFC-3986" href="http://www.rfc-editor.org/rfc/rfc3986.txt" target="_blank">RFC-3986</a>. This means a URI of: <strong>t-data</strong> is just as valid as: <strong>http://www.somethign.com/xml</strong> (we&#8217;ll see this in action below in the next example where we use the namespace: <em>a-non-url-namespace</em>).</p>
<p>Using XPath with the manual method is, again, the same, but now we add the extra mental kink that although we&#8217;ve already defined the prefix, we need not respect it in the registerXPathNamespace() function call:</p>
<pre>$namespaces_manual = &lt;&lt;&lt;EOG
&lt;root&gt;
 &lt;h:html xmlns:h="http://www.somethign.com/html"&gt;
 &lt;h:table&gt;
 &lt;h:a&gt;Good Stuff&lt;/h:a&gt;
 &lt;/h:table&gt;
 &lt;/h:html&gt;    

 &lt;x:xmlnode xmlns:x="a-non-url-namespace"&gt;
 &lt;x:table&gt;
 &lt;x:a&gt;Good Stuff 2&lt;/x:a&gt;
 &lt;/x:table&gt;
 &lt;/x:xmlnode&gt;
&lt;/root&gt;
EOG;

$t_xml = new SimpleXMLElement($namespaces_manual);

$t_xml-&gt;registerXPathNamespace("random-identifier", "a-non-url-namespace");

$data = $t_xml-&gt;xpath("//random-identifier:a");

var_dump($data);
// array(1) {   [0]=&gt;   object(SimpleXMLElement)#3 (1) {     [0]=&gt;     string(12) "Good Stuff 2"   } }</pre>
<p>As you can see, although the XML document has specified <strong>x</strong> as the prefix for the: <em>a-non-url-namespace </em>namespace, we redefine this for the xpath() call in registerXPathNamespace() as <em>random-identifier. </em>Again, perfectly legal, and the cause of much confusion when learning this topic!</p>
<p>The one thing we can&#8217;t change however, is the mapping of the namespace. As described above note how we&#8217;ve changed the URI to be a simple text string. So long as the value defined in the XML document and the call to registerXPathNamespace() match, we&#8217;re good to go.</p>
<h2>A Real-world Example</h2>
<p>Lets put our knowledge to use by taking a look at a real XML response from an actual <a title="StockQuote Web Service" href="http://www.webservicex.net/stockquote.asmx?WSDL" target="_blank">SOAP web service</a>.</p>
<pre>&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="[hidden-for-brevity]" xmlns:xsd="[hidden-for-brevity]"&gt;
 &lt;soap:Body&gt;
 &lt;GetQuoteResponse xmlns="http://www.webserviceX.NET/"&gt;
 &lt;GetQuoteResult&gt;
 &lt;StockQuotes&gt;
 &lt;Stock&gt;
 &lt;Symbol&gt;IBM&lt;/Symbol&gt;
 &lt;Last&gt;172.24&lt;/Last&gt;
 &lt;Date&gt;5/12/2011&lt;/Date&gt;
 &lt;Time&gt;4:02pm&lt;/Time&gt;
 &lt;Change&gt;+2.74&lt;/Change&gt;
 &lt;Open&gt;169.43&lt;/Open&gt;
 &lt;High&gt;172.77&lt;/High&gt;
 &lt;Low&gt;168.65&lt;/Low&gt;
 &lt;Volume&gt;5142809&lt;/Volume&gt;
 &lt;MktCap&gt;208.6B&lt;/MktCap&gt;
 &lt;PreviousClose&gt;169.50&lt;/PreviousClose&gt;
 &lt;PercentageChange&gt;+1.62%&lt;/PercentageChange&gt;
 &lt;AnnRange&gt;120.61 - 173.54&lt;/AnnRange&gt;
 &lt;Earns&gt;11.911&lt;/Earns&gt;
 &lt;P-E&gt;14.23&lt;/P-E&gt;
 &lt;Name&gt;International Bus&lt;/Name&gt;
 &lt;/Stock&gt;
 &lt;/StockQuotes&gt;
 &lt;/GetQuoteResult&gt;
 &lt;/GetQuoteResponse&gt;
 &lt;/soap:Body&gt;
&lt;/soap:Envelope&gt;</pre>
<p>Question: how would we query the <em>Last </em>node? (the stock price value, not the actual last node of the document)</p>
<p>Right at the very top of the document we have a slew of namespace definitions:</p>
<pre>&lt;soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="[hidden]" xmlns:xsd="[hidden]"&gt;</pre>
<p>What&#8217;s important to note is when we scan through the rest of the XML response we&#8217;ll note that only the first namespace definition is actually used:</p>
<pre>&lt;soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" [...] &gt;</pre>
<p>&#8230;the rest are not. This is typical of many responses, where the goal of being generic leads to a touch of extra code that may or may not be used. Don&#8217;t be thrown or confused by this extra code!</p>
<p>Regardless, for the first definition remember the pattern: <em>prefix</em>:<em>node-name</em>.</p>
<p>Thus, our <em>Envelope </em>node prefix is <em>soap.</em> <em>soap</em>, as a prefix, is then mapped/defined immediately after as: <strong>xmlns:soap=&#8221;http://schemas.xmlsoap.org/soap/envelope/</strong>&#8220;. Note that syntax. We say we have a prefix called soap, to define the namespace for that prefix we use the keyword <em>xmlns</em>, a colon (:), and the prefix we wish to define wrapped in quotes. Hence: <strong>xmlns:soap=&#8221;http://schemas.xmlsoap.org/soap/envelope/&#8221;</strong>.</p>
<p>So we know we have a prefix called soap that&#8217;s has a namespace of: <strong>http://schemas.xmlsoap.org/soap/envelope/</strong>. This is of course vital when it comes to the xpath() call, as before we can get anywhere with our query we&#8217;ll need to remember that any child element of this node will need to use that namespace.</p>
<p>The next line down then:</p>
<pre>&lt;soap:Body&gt;</pre>
<p>Says: &#8220;right&#8211;I&#8217;m the <em>Body </em>node, and because I&#8217;m part of the soap namespace block, I have <strong>soap:</strong> written before my node name.</p>
<p>The next line throws us for a loop:</p>
<pre>&lt;GetQuoteResponse xmlns="http://www.webserviceX.NET/"&gt;</pre>
<p>As you&#8217;ll recall, the document has now defined a Default Namespace for <em>GetQuoteResponse</em>&#8211;why?</p>
<p>Well, first recall that a Default Namespace definition means that all child nodes of this guy need not use the prefix syntax. Critically, this means the namespace we&#8217;ve just defined: <strong>http://www.webserviceX.NET/</strong>, is in theory only. It has no prefix value, which means in our registerXPathNamespace() call we&#8217;ll essentially be defining it on the fly.</p>
<p>It also means that the child nodes of <em>GetQuoteResponse </em>look like standard XML, even though they&#8217;re part of the <strong>http://www.webserviceX.NET/</strong> namespace.</p>
<p>This is of course one of the downsides to the Default Namespace syntax, in that in a long or poorly formatted XML file we may not realize the namespace relationship exists.</p>
<p>Regardless, also important to understanding what this means is to know that we can <em>nest </em>namespace definitions. This means that even though we&#8217;re already within the scope of the <em>soap </em>prefix/namespace, by defining a new namespace we&#8217;re saying this one no longer matters.</p>
<p>When we scan through the rest of the document then we&#8217;ll see that no other namespaces are defined, which means ultimately our xpath logic will take the form of:</p>
<pre>$soap_response_xml = &lt;&lt;&lt;EOD
&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;
 &lt;soap:Body&gt;
 &lt;GetQuoteResponse xmlns="http://www.webserviceX.NET/"&gt;
 &lt;GetQuoteResult&gt;
 &lt;StockQuotes&gt;
 &lt;Stock&gt;
 &lt;Symbol&gt;IBM&lt;/Symbol&gt;
 &lt;Last&gt;172.24&lt;/Last&gt;
 &lt;Date&gt;5/12/2011&lt;/Date&gt;
 &lt;Time&gt;4:02pm&lt;/Time&gt;
 &lt;Change&gt;+2.74&lt;/Change&gt;
 &lt;Open&gt;169.43&lt;/Open&gt;
 &lt;High&gt;172.77&lt;/High&gt;
 &lt;Low&gt;168.65&lt;/Low&gt;
 &lt;Volume&gt;5142809&lt;/Volume&gt;
 &lt;MktCap&gt;208.6B&lt;/MktCap&gt;
 &lt;PreviousClose&gt;169.50&lt;/PreviousClose&gt;
 &lt;PercentageChange&gt;+1.62%&lt;/PercentageChange&gt;
 &lt;AnnRange&gt;120.61 - 173.54&lt;/AnnRange&gt;
 &lt;Earns&gt;11.911&lt;/Earns&gt;
 &lt;P-E&gt;14.23&lt;/P-E&gt;
 &lt;Name&gt;International Bus&lt;/Name&gt;
 &lt;/Stock&gt;
 &lt;/StockQuotes&gt;
 &lt;/GetQuoteResult&gt;
 &lt;/GetQuoteResponse&gt;
 &lt;/soap:Body&gt;
&lt;/soap:Envelope&gt;
EOD;

$t_xml = new SimpleXMLElement($soap_response_xml);

$t_xml-&gt;registerXPathNamespace("v", "http://www.webserviceX.NET/");

$data = $t_xml-&gt;xpath("//v:Last");

var_dump($data);
// array(1) {   [0]=&gt;   object(SimpleXMLElement)#3 (1) {     [0]=&gt;     string(6) "172.24"   } }</pre>
<p>In short, as the Default Namespace defined for <strong>http://www.webserviceX.NET/</strong> is the parent of the <em>Last </em>node, this is the one we ultimately end up mapping to the v prefix in registerXPathNamespace(). As the &#8216;root&#8217; of this namespace is the <em>GetQuoteResponse </em>node, a simple call of: //v:Last is all it takes to pull the value we need.</p>
<p>Remember, when using namespaces in xpath queries we must always use the namespace prefix. Thus: <strong>//Last</strong> would not work, it <em>must</em> be the fully qualified: <strong>//v:Last</strong>.</p>
<h2>Conclusion</h2>
<p>By using namespaces we effectively separate XML document into layers, with each namespace being an autonomous entity within its enclosing block (its scope).</p>
<p>For most documents we create this will not be an issue, as I would like to think we would design our data structures to avoid such complexities. However, the reality of modern web development is such that many sources of data we process <em>will </em>use namespaces, so knowing how they affect xpath() queries is vital.</p>
<p>The rub is that namespaces in XML when called via XPath are pretty cumbersome to learn, and if you&#8217;re like me, they won&#8217;t actually make sense until you copy and paste the examples above into a test page and run them for yourself. Thus, if you&#8217;re still confused, the best way forward is to play with the example until they make sense!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.formboss.net/blog/2011/05/xml-namespaces-and-xpath/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Sunspider Benchmark in C++</title>
		<link>http://www.formboss.net/blog/2011/04/sunspider-benchmark-in-c/</link>
		<comments>http://www.formboss.net/blog/2011/04/sunspider-benchmark-in-c/#comments</comments>
		<pubDate>Sat, 23 Apr 2011 20:27:54 +0000</pubDate>
		<dc:creator>grdinic</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[benchmark]]></category>
		<category><![CDATA[fannkuch]]></category>
		<category><![CDATA[sunspider]]></category>

		<guid isPermaLink="false">http://www.formboss.net/blog/?p=1168</guid>
		<description><![CDATA[The Sunspider JavaScript Benchmark is a popular test of Web Browser performance. As great as the newest browsers are I though it would be interesting to take a random test and port it to C++ for the sake of comparison. I decided the rather short fannkuch test was a good candidate. The results: Not surprisingly [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://www.webkit.org/perf/sunspider-0.9.1/sunspider-0.9.1/driver.html">Sunspider JavaScript Benchmark</a> is a <a href="http://ie.microsoft.com/testdrive/benchmarks/sunspider/default.html">popular test</a> of Web Browser performance.</p>
<p>As great as the newest browsers are I though it would be interesting to take a random test and port it to C++ for the sake of comparison.</p>
<p>I decided the rather short <a href="http://www.webkit.org/perf/sunspider-0.9/access-fannkuch.html">fannkuch </a>test was a good candidate. The results:</p>
<p><a rel="attachment wp-att-1169" href="http://www.formboss.net/blog/2011/04/sunspider-benchmark-in-c/fannkuch-benchmark/"><img class="alignnone size-full wp-image-1169" title="fannkuch-benchmark" src="http://www.formboss.net/blog/wp-content/uploads/2011/04/fannkuch-benchmark.png" alt="" width="680" height="422" /></a></p>
<p>Not surprisingly the C++ version is 18x faster than Firefox and 8x faster than Chrome. For the curious, the ported C++ code is after the jump.</p>
<p>I should mention one thing changed from the stock Sunspider site (e.g., the link above), is the number of iterations was upped from 8 to 10. At 8 iterations the C++ version was sub-millisecond, meaning I&#8217;d have had to roll a custom assembly timer to get a benchmark value. That said, when we lower the iterations down to 9, the stack heavy algorithm starts to benefit the browsers more, with Chrome coming in only 3 times slower and Firefox 11. </p>
<p>Lower the iteration count to the &#8220;stock&#8221; 8 and Firefox actually catches up to Chrome, with both browsers reporting ~21ms. Interesting. </p>
<p><span id="more-1168"></span></p>
<p>The C++ Code</p>
<pre class="brush: cpp; title: ; notranslate">
int MainWindow::Fannkuch(int n)
{

    int check = 0;
    int perm[n];
    int perm1[n];
    int count[n];
    int maxPerm[n];
    int maxFlipsCount = 0;
    int m = n - 1;

    for (int i = 0; i &lt; n; i++){
        perm1[i] = i;
    }

    int r = n;

    while (true) {

        // write-out the first 30 permutations
        if (check &lt; 30){
            int s = 0;
            for(int i=0; i&lt;n; i++) s += (perm1[i]+1);
            check++;
        }

        while (r != 1) { count[r - 1] = r; r--; }

        if (!(perm1[0] == 0 || perm1[m] == m)) {
            for (int i = 0; i &lt; n; i++) perm[i] = perm1[i];
            int flipsCount = 0;
            int k;

            while (!((k = perm[0]) == 0)) {
                int k2 = (k + 1) &gt;&gt; 1;
                for (int i = 0; i &lt; k2; i++) {
                    int temp = perm[i]; perm[i] = perm[k - i]; perm[k - i] = temp;
                }
                flipsCount++;
            }

            if (flipsCount &gt; maxFlipsCount) {
                maxFlipsCount = flipsCount;
                for (int i = 0; i &lt; n; i++) maxPerm[i] = perm1[i];
            }
        }

        while (true) {
            if (r == n) return maxFlipsCount;

            int perm0 = perm1[0];
            int i = 0;

            while (i &lt; r) {
                int j = i + 1;
                perm1[i] = perm1[j];
                i = j;
            }

            perm1[r] = perm0;
            count[r] = count[r] - 1;

            if (count[r] &gt; 0) break;
            r++;
        }
    }

}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.formboss.net/blog/2011/04/sunspider-benchmark-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

