<?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>Блог Костика &#187; JavaScript</title>
	<atom:link href="http://blog.piterpen.net/category/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.piterpen.net</link>
	<description>42</description>
	<lastBuildDate>Tue, 27 Jul 2010 09:46:56 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=abc</generator>
		<item>
		<title>Yet another faster JavaScript sorting</title>
		<link>http://blog.piterpen.net/2007/01/08/7/</link>
		<comments>http://blog.piterpen.net/2007/01/08/7/#comments</comments>
		<pubDate>Mon, 08 Jan 2007 19:12:43 +0000</pubDate>
		<dc:creator>kostik</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[English]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[работа]]></category>

		<guid isPermaLink="false">http://blog.piterpen.net/2007/01/08/yet-another-faster-javascript-sorting/</guid>
		<description><![CDATA[It&#160;is&#160;no&#160;secret that the demand on&#160;applications with &#8220;AJAX&#8221; in&#160;the name is&#160;continually increasing. Nolens volens one has to&#160;do&#160;some things with unadapted to&#160;them tools: an&#160;illustration in&#160;point is&#160;Internet Explorer&#160;&#8212; a&#160;program which is&#160;unadapted to&#160;execution of&#160;the code that would be&#160;standardized and had a&#160;common sense. Recently I&#160;had &#8230; <a href="http://blog.piterpen.net/2007/01/08/7/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>It&nbsp;is&nbsp;no&nbsp;secret that the demand on&nbsp;applications with &ldquo;AJAX&rdquo; in&nbsp;the name is&nbsp;continually increasing. Nolens volens one has to&nbsp;do&nbsp;some things with unadapted to&nbsp;them tools: an&nbsp;illustration in&nbsp;point is&nbsp;Internet Explorer&nbsp;&mdash; a&nbsp;program which is&nbsp;unadapted to&nbsp;execution of&nbsp;the code that would be&nbsp;standardized and had a&nbsp;common sense. Recently I&nbsp;had to&nbsp;deal with one of&nbsp;its problems. I&nbsp;had to&nbsp;sort out an&nbsp;array of&nbsp;objects by&nbsp;the given field. IE&nbsp;did it&nbsp;100&nbsp;times slower than FireFox! Solution allows sorting out six times faster than Internet Explorer. A&nbsp;link to&nbsp;the library implementing this method follows. <span id="more-7"></span></p>
<h3>Problem</h3>
<p>With trivial code</p>
<p>// Array а&nbsp;contains 15000&nbsp;elements<br />
a.sort(function(a,&nbsp;b){return b.item&nbsp;&mdash; a.item;})</p>
<p>IE&nbsp;needs 40(!) seconds to&nbsp;think (15000&nbsp;was taken as&nbsp;a&nbsp;test, a&nbsp;real array is&nbsp;certainly less). (FireFox does the same in&nbsp;422ms, approximately 100&nbsp;times faster!) The realization of&nbsp;the sorting process on&nbsp;the server side would require changing of&nbsp;a&nbsp;large part of&nbsp;the code because the user selects a&nbsp;field and a&nbsp;method of&nbsp;sorting; this was a&nbsp;problem.</p>
<h3>Solution</h3>
<p>After short googling I&nbsp;found an&nbsp;<a href="http://www.lindsay.id.au/blog/?p=6">excellent article by&nbsp;Russel Lindsay: &ldquo;Faster Javascript sorting&rdquo;</a>. He&nbsp;uses a&nbsp;simple trick: to&nbsp;rewrite the method toString() for addressing to&nbsp;the object&#8217;s property directly, convert numbers ([1, 2,&nbsp;10]&nbsp;into strings ['01','02','10']) and use sort() without parameters for increasing sorting speed. Below the results of&nbsp;the test (with my&nbsp;implementation of&nbsp;this idea):</p>
<pre>Internet Explorer41516ms – sort(function(a, b){return b.item - a.item;})

7031ms - sort() for the array where numbers were converted into string

7047ms – sort() and reverse() for the array where numbers were converted into stringFireFox

438ms – sort(function(a, b){return b.item - a.item;})

891ms - sort() for the array where numbers were converted into string

954ms – sort() and reverse() for the array where numbers were converted into string</pre>
<p>Thus the trick of&nbsp;adding numbers with zeros to&nbsp;strings gives a&nbsp;six times quicker sorting in&nbsp;Internet Explorer and twice slower sorting in&nbsp;FF&nbsp;which allows using the code in&nbsp;both browsers.</p>
<p>Russel Lindsay uses the fixed size mask and the array ([1, 2,&nbsp;10]&nbsp;turns not into [01, 02,&nbsp;10]&nbsp;but into ['00000000001',' 00000000002',' 00000000010']). This is&nbsp;awful for many reasons and memory used is&nbsp;one of&nbsp;them. So&nbsp;I&nbsp;wrote a&nbsp;small library based on&nbsp;his code. It&nbsp;adds to&nbsp;Array() following methods: Array.sortIntAsc(property) and Array.sortIntDesc(property) for sorting array by&nbsp;integer property, Array.sortAsc(property), and Array.sortDesc(property) for sorting by&nbsp;string property.</p>
<h3>Example</h3>
<p>[js] var team = [<br />
{name:&rsquo;Bill&rsquo;, age:25},<br />
{name:&rsquo;John&rsquo;, age:21},<br />
{name:&rsquo;Ann&rsquo;, age:20}<br />
];</p>
<p>alert([team[0].name,team[1].name,team[2].name]);<br />
// Bill, John, Ann</p>
<p>team.sortIntAsc(&rsquo;age&rsquo;);<br />
alert([team[0].name,team[1].name,team[2].name]);<br />
// Ann, John, Bill</p>
<p>team.sortAsc(&rsquo;name&rsquo;);<br />
alert([team[0].name,team[1].name,team[2].name]);<br />
// Ann, Bill, John</p>
<p>[/js]</p>
<h3>My&nbsp;2&nbsp;cents</h3>
<p>This method is&nbsp;in&nbsp;my&nbsp;humble opinion a&nbsp;good solution of&nbsp;this particular problem (thank you, <a href="http://www.lindsay.id.au/blog/?p=6">Russel</a>!). Also it&nbsp;is&nbsp;a&nbsp;good illustration: the best way to&nbsp;do&nbsp;something with data in&nbsp;the Internet Explorer is&nbsp;not to&nbsp;do&nbsp;anything. I&nbsp;mean to&nbsp;organize the data processing flow in&nbsp;such a&nbsp;way as&nbsp;to&nbsp;leave the data processing (including any sorting) on&nbsp;the server side. Otherwise when IE&nbsp;will deal with trivial tasks terrible you will have to&nbsp;spend a&nbsp;lot of&nbsp;time to&nbsp;find a&nbsp;strange detour.</p>
<p><a href="http://blog.piterpen.net/wp-content/uploads/2007/01/arraysort.zip"> download library (zip)</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.piterpen.net/2007/01/08/7/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Быстрая сортировка в JavaScript</title>
		<link>http://blog.piterpen.net/2007/01/08/6/</link>
		<comments>http://blog.piterpen.net/2007/01/08/6/#comments</comments>
		<pubDate>Mon, 08 Jan 2007 18:50:03 +0000</pubDate>
		<dc:creator>kostik</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[работа]]></category>

		<guid isPermaLink="false">http://blog.piterpen.net/2007/01/08/%d0%b1%d1%8b%d1%81%d1%82%d1%80%d0%b0%d1%8f-%d1%81%d0%be%d1%80%d1%82%d0%b8%d1%80%d0%be%d0%b2%d0%ba%d0%b0-%d0%b2-javascript/</guid>
		<description><![CDATA[Не секрет, что спрос на приложения c приставкой “AJAX” постоянно растет. Волей-неволей приходится делать некоторые вещи неприспособленными для этого инструментами: характерным примером является Internet Explorer – программа, однозначно неприспособленная для выполнения кода, соответствующего стандарту и здравому смыслу. С одной из &#8230; <a href="http://blog.piterpen.net/2007/01/08/6/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Не секрет, что спрос на приложения c приставкой “AJAX” постоянно растет. Волей-неволей приходится делать некоторые вещи неприспособленными для этого инструментами: характерным примером является Internet Explorer – программа, однозначно неприспособленная для выполнения кода, соответствующего стандарту и здравому смыслу. С одной из его проблем мне пришлось столкнуться: мне понадобилось отсортировать по заданному полю массив объектов. Выяснилось, что сортировка в IE работает в 100 раз медленнее, чем в FireFox. В результате было найдено решение, которое позволяет сортировать примерно в 6 раз быстрее, чем это делает Internet Explorer, ниже есть ссылка на библиотеку, которая реализует этот метод.<span id="more-6"></span></p>
<h3>Проблема</h3>
<p>Тривиальное</p>
<p>// Object а содержит 15000 элементов<br />
a.sort(function(a, b){return b.item &#8211; a.item;})</p>
<p>заставило IE задуматься на 40(!) секунд (15000 взято в качестве теста, реальный массив, конечно, меньше). (FireFox выполнял тот же за 422ms, примерно в 100 раз быстрее!) Реализация сортировки на стороне сервера потребовала бы изменить много кода, так как поле и направление сортировки выбирались пользователем произвольно; это была проблема.</p>
<h3>Решение</h3>
<p>После недолгих поисков я обнаружил <a href="http://weetbixthecat.com/blog/2006/faster-javascript-sorting/" target="_blank">отличную статью Russel Lindsay: “Faster Javascript sorting”</a>. Он использует очень простую вещь: переписать метод toString() для обращения к свойству объекта, превратить числа в строки ([1, 2, 10] в [’01’,’02’,’10’]) и использовать sort() без параметров для ускорения поиска. Вот результаты тестов:</p>
<pre>Internet Explorer
41516ms – sort(function(a, b){return b.item - a.item;})
7031ms - sort() для массива, где числа конвертированы в строки
7047ms – sort() и reverse() для массива, где числа конвертированы в строки

FireFox
438ms – sort(function(a, b){return b.item - a.item;})
891ms - sort() для массива, где числа конвертированы в строки
954ms – sort() и reverse() для массива, где числа конвертированы в строки</pre>
<p>Таким образом, фокус с дополнением чисел нолями до строк дает выигрыш примерно в 6 раз при сортировке в Internet Explorer, и проигрыш всего вдвое при сортировке в FF, что позволяет использовать код в обоих браузерах.</p>
<p>Russel Lindsay использует маску фиксированного размера, то есть массив ([1, 2, 10] превращается не в [01, 02, 10], а в [’00000000001’,’ 00000000002’,’ 00000000010’]), это ужасно по многим причинам, и память – не последняя из них. Так что я написал маленькую библиотеку на основе его кода, она расширяет Array() методами Array.sortIntAsc(property) и Array.sortIntDesc(property) для сортировки по числовому полю property, и методами Array.sortAsc(property) и Array.sortDesc(property) для сортировки по строковому полю property.</p>
<p>Пример</p>
<p>[js] var    team = [<br />
{name:'Bill', age:25},<br />
{name:'John', age:21},<br />
{name:'Ann', age:20}<br />
];</p>
<p>alert([team[0].name,team[1].name,team[2].name]);<br />
// Bill, John, Ann</p>
<p>team.sortIntAsc(&#8216;age&#8217;);<br />
alert([team[0].name,team[1].name,team[2].name]);<br />
// Ann, John, Bill</p>
<p>team.sortAsc(&#8216;name&#8217;);<br />
alert([team[0].name,team[1].name,team[2].name]);<br />
// Ann, Bill, John</p>
<p>[/js]</p>
<p><script type="text/javascript"> <script> var    team = [ {name:\'Bill\', age:25}, {name:\'John\', age:21}, {name:\'Ann\', age:20} ];</p>
<p>alert([team[0].name,team[1].name,team[2].name]); // Bill, John, Ann</p>
<p>team.sortIntAsc(\'age\'); alert([team[0].name,team[1].name,team[2].name]); // Ann, John, Bill</p>
<p>team.sortAsc(\'name\'); alert([team[0].name,team[1].name,team[2].name]); // Ann, Bill, John</p>
<p></script></p>
<h3>Мои 5 копеек</h3>
<p>Этот метод, мне кажется, неплохое решение конкретной проблемы. Но это так же прекрасная иллюстрация:  лучший способ сделать что-то с данными в Internet Explorer – это не делать совсем, то есть организовать модель так, что бы вся обработка данных (включая сортировку) осталась на стороне сервера. Иначе потом, когда IE будет отвратительно справляться с очевидными задачами, придется потратить немало сил на обход проблемы.</p>
<p><a href="http://blog.piterpen.net/wp-content/uploads/2007/01/arraysort.zip" target="_blank">скачать библиотеку</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.piterpen.net/2007/01/08/6/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
	</channel>
</rss>
