<?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</title>
	<atom:link href="http://www.formboss.net/blog/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>MySQL INSERT SELECT Statements</title>
		<link>http://www.formboss.net/blog/2011/10/mysql-insert-select-statements/</link>
		<comments>http://www.formboss.net/blog/2011/10/mysql-insert-select-statements/#comments</comments>
		<pubDate>Mon, 10 Oct 2011 17:20:29 +0000</pubDate>
		<dc:creator>grdinic</dc:creator>
				<category><![CDATA[MySQL]]></category>
		<category><![CDATA[INSERT SELECT]]></category>

		<guid isPermaLink="false">http://www.formboss.net/blog/?p=1440</guid>
		<description><![CDATA[That&#8217;s not a typo, it&#8217;s a real feature of MySQL, and one I just learned about. The basic idea is to SELECT rows from one or more tables to populate another. It does this with a temp table, and for the most part respects things like auto-increment fields and foreign key restraints. It&#8217;s a neat [...]]]></description>
			<content:encoded><![CDATA[<pre class="brush: sql; title: ; notranslate">
INSERT INTO tbl_temp2 (fld_id)
SELECT tbl_temp1.fld_order_id
FROM tbl_temp1 WHERE tbl_temp1.fld_order_id &gt; 100;
</pre>
<p>That&#8217;s not a typo, it&#8217;s a <a title="MySQL Insert Select" href="http://dev.mysql.com/doc/refman/5.1/en/insert-select.html" target="_blank">real feature of MySQL</a>, and one I just learned about. The basic idea is to SELECT rows from one or more tables to populate another. It does this with a temp table, and for the most part respects things like auto-increment fields and foreign key restraints.</p>
<p>It&#8217;s a neat little trick that should help with those times where we&#8217;ve been populating temp tables with incremental updates, and now need to create one final INSERT into a master table.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.formboss.net/blog/2011/10/mysql-insert-select-statements/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>GCC Vs. LLVM &#8211; Simple Test Code Optimizations</title>
		<link>http://www.formboss.net/blog/2011/09/gcc-vs-llvm-simple-low-level-optimizations/</link>
		<comments>http://www.formboss.net/blog/2011/09/gcc-vs-llvm-simple-low-level-optimizations/#comments</comments>
		<pubDate>Thu, 29 Sep 2011 05:04:13 +0000</pubDate>
		<dc:creator>grdinic</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[Clang]]></category>
		<category><![CDATA[GCC]]></category>
		<category><![CDATA[LLVM]]></category>

		<guid isPermaLink="false">http://www.formboss.net/blog/?p=1412</guid>
		<description><![CDATA[As a companion piece to this test suite on Phoronix I took the following *very simple* code and ran it though GCC 4.6 (Fedora 15) and the Clang/LLVM 2.8 Suite to check performance and various optimizations being performed: This code is purpose built to thwart basic compiler optimizations. In particular the printf() call at the [...]]]></description>
			<content:encoded><![CDATA[<p>As a companion piece to this test suite on <a href="http://www.phoronix.com/scan.php?page=article&amp;item=gcc_46_llvm29&amp;num=1">Phoronix</a> I took the following *very simple* code and ran it though GCC 4.6 (Fedora 15) and the Clang/LLVM 2.8 Suite to check performance and various optimizations being performed:</p>
<pre class="brush: cpp; title: ; notranslate">
#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;

int test_noRef(int value)
{
	return value + 1;
}

int test_ref(int &amp;value){
	return value += 1;
}

int main(int argc, char *argv[]){

	int t = 1;

	for(int i = 0; i &lt; 100000000; i++){
		//t = test_noRef(t);
		test_ref(t);
	}

	// final result = n loops + 1
	printf(&quot;%d\n&quot;, t);

}
</pre>
<p><span id="more-1412"></span></p>
<p>This code is purpose built to thwart basic compiler optimizations. In particular the printf() call at the end prevents the compilers from simply skipping the entire function call block.</p>
<p>While simplistic, the basic idea is to see what optimizations each compiler performs and at what optimization level. Note that the LLVM/Clang suite can easily be installed on Fedora 15 by searching for LLVM. You&#8217;ll want to install LLVM <em>and </em>Clang:</p>
<p><a href="http://www.formboss.net/blog/2011/09/gcc-vs-llvm-simple-low-level-optimizations/llvm-clang-install/" rel="attachment wp-att-1414"><img class="alignnone size-full wp-image-1414" title="llvm-clang-install" src="http://www.formboss.net/blog/wp-content/uploads/2011/09/llvm-clang-install.png" alt="" width="675" height="558" /></a></p>
<h2>No Optimizations</h2>
<p>We start with a basic compile with no optimizations; in each case we&#8217;ll focus on test_ref() and test_noRef(). Please note I&#8217;ve removed the stack management code from these listings as they differ very little by compiler.</p>
<pre class="brush: plain; title: ; notranslate">
g++ main.cpp -S
clang main.cpp -S
</pre>
<p>[GCC]</p>
<pre class="brush: plain; title: ; notranslate">
_Z10test_noRefi:
.LFB0:
	movl	%edi, -4(%rbp)
	movl	-4(%rbp), %eax
	addl	$1, %eax
	popq	%rbp
	.cfi_def_cfa 7, 8
	ret
</pre>
<p>The noRef call in GCC moves our parameter to eax, adds 1, and cleans up the stack.</p>
<p>[LLVM]</p>
<pre class="brush: plain; title: ; notranslate">
_Z10test_noRefi:
.Leh_func_begin0:
	pushq	%rbp
.Ltmp0:
	movq	%rsp, %rbp
.Ltmp1:
	movl	%edi, -4(%rbp)
	movl	-4(%rbp), %edi
	addl	$1, %edi
	movl	%edi, %eax
	popq	%rbp
	ret
</pre>
<p>The LLMV code for the noRef() function is quite similar. The main difference is LLVM uses edi for the addition step, then pushes the result to eax before returning.</p>
<p>[GCC]</p>
<pre class="brush: plain; title: ; notranslate">
_Z8test_refRi:
.LFB1:
	movq	%rdi, -8(%rbp)
	movq	-8(%rbp), %rax
	movl	(%rax), %eax
	leal	1(%rax), %edx
	movq	-8(%rbp), %rax
	movl	%edx, (%rax)
	movq	-8(%rbp), %rax
	movl	(%rax), %eax
	popq	%rbp
	.cfi_def_cfa 7, 8
	ret
</pre>
<p>The reference using version performs the same basic logic, but instead of using movl we issue movq, which means our parameters are twice as large. That inefficiency aside we do use an optimization for adding the 1 to our input argument via the leal instruction.</p>
<p>[LLVM]</p>
<pre class="brush: plain; title: ; notranslate">
_Z8test_refRi:
.Leh_func_begin1:
	pushq	%rbp
.Ltmp3:
	movq	%rsp, %rbp
.Ltmp4:
	movq	%rdi, -8(%rbp)
	movq	-8(%rbp), %rdi
	movl	(%rdi), %eax
	addl	$1, %eax
	movl	%eax, (%rdi)
	popq	%rbp
	ret
</pre>
<p>LLVM&#8217;s code is a bit cleaner, focusing on pulling the value from the stack, performing the addl, and retuning the result.</p>
<p>[GCC]</p>
<pre class="brush: plain; title: ; notranslate">
main:
.L5:
	leaq	-8(%rbp), %rax
	movq	%rax, %rdi
	call	_Z8test_refRi
	addl	$1, -4(%rbp)
.L4:
	cmpl	$99999999, -4(%rbp)
	setle	%al
	testb	%al, %al
	jne	.L5
	movl	-8(%rbp), %eax
	movl	%eax, %esi
	movl	$.LC0, %edi
	movl	$0, %eax
	call	printf
	movl	$0, %eax
	leave
</pre>
<p>As with the function calls I&#8217;ve removed the activation record code. LLVM&#8217;s main function definition is essentially the same, so we won&#8217;t cover it here.</p>
<p>A quick benchmark between the two shows what we would expect from the extra fluff in GCC&#8217;s implementation:</p>
<p><strong>GCC</strong><br />
real 0m0.407s<br />
user 0m0.405s<br />
sys 0m0.002s</p>
<p><strong>LLVM</strong><br />
real 0m0.396s<br />
user 0m0.394s<br />
sys 0m0.000s</p>
<h2>Level 1 Optimizations</h2>
<p>It&#8217;s a bit unfair to draw comparisons without some optimizations turned on, so let&#8217;s do so now:</p>
<pre class="brush: plain; title: ; notranslate">
g++ main.cpp -O1 -S
clang main.cpp -O1 -S
</pre>
<p>[GCC]</p>
<pre class="brush: plain; title: ; notranslate">
_Z10test_noRefi:
.LFB19:
	leal	1(%rdi), %eax
	ret
</pre>
<p>Already we can see a huge difference in GCC&#8217;s output, which whittles this call down to a simple Load Effective Address and return.</p>
<p>[LLVM]</p>
<pre class="brush: plain; title: ; notranslate">
_Z10test_noRefi:
	leal	1(%rdi), %eax
	popq	%rbp
	ret
</pre>
<p>As expected LLVM performs the same lea optimization as GCC.</p>
<p>[GCC]</p>
<pre class="brush: plain; title: ; notranslate">
_Z8test_refRi:
.LFB20:
	movl	(%rdi), %eax
	addl	$1, %eax
	movl	%eax, (%rdi)
	ret
</pre>
<p>The reference-using version still has to contend with the indirection call via movl ($rdi), %eax, but still a good improvement.</p>
<p>[LLVM]</p>
<pre class="brush: plain; title: ; notranslate">
.Ltmp4:
	movl	(%rdi), %eax
	incl	%eax
	movl	%eax, (%rdi)
	popq	%rbp
	ret
</pre>
<p>LLVM is using incl to perform our addition call, GCC uses addl. A quick check on Google shows Intel <a href="http://mail.openjdk.java.net/pipermail/hotspot-compiler-dev/2009-January/000547.html">recommends the GCC way</a>.</p>
<p>[GCC]</p>
<pre class="brush: plain; title: ; notranslate">
	movl	$1, 12(%rsp)
	movl	$100000000, %ebx
.L4:
	leaq	12(%rsp), %rdi
	call	_Z8test_refRi
	subl	$1, %ebx
	jne	.L4
</pre>
<p>The main() function has been reduced to the basics, counting down from our loop initialization value and calling the test_ref() function.</p>
<p>[LLVM]</p>
<pre class="brush: plain; title: ; notranslate">
.Ltmp8:
	movl	$1, -20(%rbp)
	movl	$100000000, %ebx
	leaq	-20(%rbp), %r14
	.align	16, 0x90
.LBB2_1:
	movq	%r14, %rdi
	callq	_Z8test_refRi
	decl	%ebx
	jne	.LBB2_1
</pre>
<p>LLVM&#8217;s main function loop has also been optimized, though again we&#8217;re using decl instead of subl.</p>
<p>Although the two compilers perform similar optimizations here, lets examine how LLVM&#8217;s structured our reference value for the loop.</p>
<p>Right before the main loop it calls:</p>
<pre class="brush: plain; title: ; notranslate">leaq    -20(%rbp), %r14</pre>
<p>Which maps the address at that base-pointer location to r14. In essence its created an alias. Why it&#8217;s done this make sense when we see the rest of the loop.</p>
<p>The first call of every iteration is:</p>
<pre class="brush: plain; title: ; notranslate">movq	%r14, %rdi</pre>
<p>So we pass the address in %r14 to rdi and in the function call we have:</p>
<pre class="brush: plain; title: ; notranslate">movl    (%rdi), %eax</pre>
<p>Which essentially means dereference the value in rdi and push to eax for the incl call. That gets us our added value but it&#8217;s the next call where the magic happens, where we tie the whole thing together:</p>
<pre class="brush: plain; title: ; notranslate">movl    %eax, (%rdi)</pre>
<p>Now we&#8217;ve moved the value of eax to the <em>address location</em> in rdi. Since that address and the one in %r14 are one in the same, the next call in the main loop to:</p>
<pre class="brush: plain; title: ; notranslate">movq    %r14, %rdi</pre>
<p>Means that his freshly increased value from the function call being pointed to by %r14 is once again pushed to rdi, which in turn is dereferenced in the function call and incremented.</p>
<p>That&#8217;s a pretty neat bit of optimization so let&#8217;s see how it pans out in terms of performance:</p>
<p><strong>GCC</strong><br />
real 0m0.165s<br />
user 0m0.163s<br />
sys 0m0.001s</p>
<p><strong>LLVM</strong><br />
real 0m0.163s<br />
user 0m0.161s<br />
sys 0m0.001s</p>
<p>It&#8217;s much the same, as GCC performs a similar trick using %rdi and the stack.</p>
<h2>Level 2 Optimizations</h2>
<p>Finally, let&#8217;s enable the highest level of optimization:</p>
<pre class="brush: plain; title: ; notranslate">
g++ main.cpp -O2 -S
clang main.cpp -O2 -S
</pre>
<p>[GCC]</p>
<pre class="brush: plain; title: ; notranslate">
main:
.LFB21:
	.cfi_startproc
	subq	$8, %rsp
	.cfi_def_cfa_offset 16
	movl	$100000001, %esi
	movl	$.LC0, %edi
	xorl	%eax, %eax
	call	printf
	xorl	%eax, %eax
	addq	$8, %rsp
	.cfi_def_cfa_offset 8
	ret
	.cfi_endproc
</pre>
<p>[LLVM]</p>
<pre class="brush: plain; title: ; notranslate">
.Ltmp7:
	movl	$.L.str, %edi
	movl	$100000001, %esi
	xorb	%al, %al
	callq	printf
	xorl	%eax, %eax
	popq	%rbp
	ret
</pre>
<p>No need to show anything other than main() because it doesn&#8217;t matter.</p>
<p>Both LLVM and GCC have done what we&#8217;d expect with such a silly bit of code. Both compilers analyzed the code and came to the same conclusion: the final output value to prinf() can be calculated directly within the compiler, so no need to call anything. Just push 100000001 to %esi for printf() and call it a day : )</p>
<h3>In Conclusion</h3>
<p>While the code tested was simple, it&#8217;s interesting to see how the actual assembly differs. It&#8217;s clear that this simple test LLVM produces faster binaries, though not by much.</p>
<p>The other important bit is at least on Fedora, installing and using GCC and LLVM couldn&#8217;t be simpler.</p>
<h3>Links</h3>
<p><a href="http://llvm.org/docs/GettingStarted.html#tutorial4">Installing and Using LLVM</a></p>
<p><a href="http://llvm.org/demo/index.cgi">LLVM Online Compiler Demo</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.formboss.net/blog/2011/09/gcc-vs-llvm-simple-low-level-optimizations/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP 5.4 Brings Performance Improvements</title>
		<link>http://www.formboss.net/blog/2011/09/php-5-4-brings-performance-improvements/</link>
		<comments>http://www.formboss.net/blog/2011/09/php-5-4-brings-performance-improvements/#comments</comments>
		<pubDate>Tue, 27 Sep 2011 03:42:50 +0000</pubDate>
		<dc:creator>grdinic</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.formboss.net/blog/?p=1406</guid>
		<description><![CDATA[A line in the current release notes for the PHP 5.4 beta states: Sounds good to me, and after my previous post on references I thought I&#8217;d run the same test with this new build (all times are in seconds): I&#8217;d say that&#8217;s a decent improvement, though one that follows the same trend from the [...]]]></description>
			<content:encoded><![CDATA[<p>A line in the current <a title="PHP Release Notes" href="http://www.php.net/archive/2011.php#id2011-06-28-1" target="_blank">release notes</a> for the PHP 5.4 beta states:</p>
<pre class="brush: plain; title: ; notranslate">Improved: Improved Zend Engine memory usage and performance</pre>
<p>Sounds good to me, and after my previous post on <a title="PHP References" href="http://www.formboss.net/blog/2011/09/understanding-and-using-references-in-php/" target="_blank">references</a> I thought I&#8217;d run the same test<strong> </strong>with this new build (all times are in seconds):</p>
<p><a href="http://www.formboss.net/blog/2011/09/php-5-4-brings-performance-improvements/reference-test/" rel="attachment wp-att-1499"><img class="alignnone size-full wp-image-1499" title="reference-test" src="http://www.formboss.net/blog/wp-content/uploads/2011/09/reference-test.png" alt="" width="481" height="289" /></a></p>
<p>I&#8217;d say that&#8217;s a decent improvement, though one that follows the same trend from the first post of using references with objects is slower than not using them.</p>
<p>As one final test, here&#8217;s the result of loading the FormBoss.net homepage several times in succession:</p>
<p><a href="http://www.formboss.net/blog/2011/09/php-5-4-brings-performance-improvements/formboss-home-page/" rel="attachment wp-att-1501"><img class="alignnone size-full wp-image-1501" title="formboss-home-page" src="http://www.formboss.net/blog/wp-content/uploads/2011/09/formboss-home-page.png" alt="" width="481" height="289" /></a></p>
<p>So about the same when performing standard page interpreting, if not a touch slower.</p>
<h3>Links</h3>
<p><a href="http://qa.php.net/" target="_blank">http://qa.php.net/</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.formboss.net/blog/2011/09/php-5-4-brings-performance-improvements/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>
	</channel>
</rss>

