String concatenation versus array.join() in JavaScript

January 19th, 2010

To answer a question on StackOverflow, I made an experiment which actually qualifies for a separate blog post.

So, I compared the speed of str1+str2 concatenation and array.push(str1, str2).join() methods. The code I used was quite simple:

var iIterations =800000;
var d1 = (new Date()).valueOf();
str1 = "";
for (var i = 0; i<iIterations; i++) str1 = str1 + Math.random().toString();
var d2 = (new Date()).valueOf();
log("Time (strings): " + (d2-d1));

var d3 = (new Date()).valueOf();
arr1 = [];
for (var i = 0; i<iIterations; i++)arr1.push(Math.random().toString());
var str2 = arr1.join("");
var d4 = (new Date()).valueOf();
log("Time (arrays): " + (d4-d3));

I tested it in IE8 and FireFox 3.5.5, both on a Windows 7 x64.

In the beginning I tested on small number of iterations (some hundred, some thousand items). The results were unpredictable (sometimes string concatenation took 0 milliseconds, sometimes it took 16 milliseconds, the same for array joining).

When I increased the count to 50′000, the results were different in different browsers – in IE the string concatenation was faster (94 milliseconds) and join was slower(125 milliseconds), while in Firefox the array join was faster (113 milliseconds) than string joining (117 milliseconds).

Then I increased the count to 500′000. Now the array.join() was slower than string concatenation in both browsers: string concat 937ms in IE, 1155 ms in Firefox, array join 1265 in IE, 1207 in Firefox.

Maximum iteration count I could test in IE without having “the script is taking too long to execute” was 850′000. Then IE was 1593 for string concatenation and 2046 for array join, Firefox had 2101 for string concatenation and 2249 for array join.

Results – if the number of iterations is small, you can try to use array.join(), as it might be faster in Firefox. When the number increases, the string1+string2 method is faster.

UPDATE
I performed the test on IE6 (WindowsXP). The process stopped to respond immediately and never ended, if I tried the test on more than 100′000 iterations. On 40′000 iterations the results were

Time (strings): 59175 ms
Time (arrays): 220 ms

This means – if you need to support IE6, choose array.join() which is way faster than string concatenation.

Restoring the top navigation bar of a SharePoint site

December 1st, 2009

It’s a known issue that if you delete the “Top Navigation” menu through the API in SharePoint 2007, you cannot restore it easily. I came across this problem in one of my development sites. When looking for a solution, I found this article, saying you have to do it through the database.

The code below solves the problem programmatically (and yes, it changes the database directly). Of course, it’s an unsupported solution – if you use it, you may get in trouble with Microsoft official support.

string sSiteUrl = "http://moss/sites/yoursite/";
//after the code gets executed, we have to dispose the 
//spweb object, since the Navigation object of the current SPWeb instance will contain wrong information
using (SPSite oSite = new SPSite(sSiteUrl))
{
    using (SPWeb oWeb = oSite.RootWeb)
    {
        //check if the top navigation bar is already there
        SPNavigationNode oTopnav = null;
        try
        {
            oTopnav = oWeb.Navigation.GetNodeById(1002);
        }
        catch (Exception)
        {
            oTopnav = null;
        }

    if (oTopnav == null)
    {
        //we've found out there is no top navigation bar. Let's create one;

        //we create a temporary navigation node pointing back to web site root
        Microsoft.SharePoint.Navigation.SPNavigationNode oTempNode = new Microsoft.SharePoint.Navigation.SPNavigationNode("Navigation", oWeb.ServerRelativeUrl);
        //we add this node to the "global" collection (where quick launch and top nav bar normally live)
        oWeb.Navigation.GlobalNodes.AddAsLast(oTempNode);

        //now the dirty work - go to the database and change the ID of the navigation node
        System.Data.SqlClient.SqlConnection oConn = new System.Data.SqlClient.SqlConnection(oSite.ContentDatabase.DatabaseConnectionString);
        System.Data.SqlClient.SqlCommand oCmd = new System.Data.SqlClient.SqlCommand();
        oCmd.Connection = oConn;
        oCmd.CommandType = System.Data.CommandType.Text;
        //we only update the node which has the same ID as the one we just created, but, to be completely sure that 
        //nothing else gets changed, we add a requirement to have the same siteid and webid
        oCmd.CommandText = @"UPDATE NavNodes SET Eid=1002 WHERE (Eid=" + oTempNode.Id.ToString() + 
             @") AND (SiteId='" + oSite.ID.ToString("D") + "') AND (WebId='" + oWeb.ID.ToString("D") + "')"; ;
        oConn.Open();
        oCmd.ExecuteNonQuery();
        //closing the connection
        oConn.Dispose();
    }
}

} //the oSite object is disposed here

“_vti_bin” folder defined

September 11th, 2009

Ever wondered why SharePoint “lists web service” (i.e., lists.asmx) lives in an interesting address of http://mossserver/sites/somesite/_vti_bin/lists.asmx ?

This is actually not the only place where you can see the magic _vti_something. I remember myself deleting such directories from “wwwroot” quite often back in the days “everyone” used MS FrontPage. FrontPage used to create the folders “_vti_bin”, “_vti_cnf” on your computer locally as you developed a website .. and also on the server, if you used “Frontpage Extensions” for publishing. The _bin folder would normally contain executables required for FP server components (as far as I understand, something like cgi_bin).

So, even though FP is announced dead, guys from the SharePoint team apparently like the idea of puting executables in the _vti_bin folder which was used by FrontPage Extensions.

Anyway, the question is, what does the acronym “VTI” mean. Apparently, Microsoft did not develop MS FrontPage from scratch, they acquiredVermeer Technologies Inc”. Thus the name of “bin” folder in FrontPage. Thus the URL for lists.asmx in SharePoint.

Shooting yourself in the foot

October 8th, 2008

Ideja no “labās prakses” prezentācijas

  • C: You shoot yourself in the foot
  • PHP: You shoot yourself in the foot with a gun made from pieces taken from 300 other guns
  • Ruby on Rails: You want to shoot yourself in the foot, but the convention is to shoot yourself in the head

(pievienošu no sevis)

  • SharePoint: You want to shoot yourself in the foot, but first you have to “IISRESET /noforce”

MOSS & custom master pages

August 5th, 2008

I just found an interesting “feature” in MOSS publishing infrastructure. We’re designing a custom master page for our MOSS portal solution. If I recall correctly, we started with Heather Solomon’s minimal master page, but I’m not really sure.

We swiped out all of the built-in styles and layouts to achieve maximum flexibility and stylability of MOSS infrastructure. I believe this is the best choice when you have to adapt your portal to custom tailored design layout.

Well, the result was, the portal worked fine with our master page, BUT the content query web part failed. It failed every time we enabled the RSS feed feature. Instead of seeing the actual content, it showed only an error message (in Latvian, since we’re using the latvian language pack) “Šo Web daļu nevar parādīt. Lai novērstu problēmu, atveriet šo Web lapu ar Windows SharePoint Services saderīgā HTML redaktorā, piemēram, Microsoft Office SharePoint Designer. Ja problēma netiek novērsta, sazinieties ar Web servera administratoru.”

No traces could be found in the ULS log nor in the event log of the server. After setting the diagnostic logging of all categories to verbose, finally an exception was written to the logfile:

 Error while executing web part: System.Xml.Xsl.XslTransformException: An error occurred during a
 call to extension function 'RegisterFeedUrl'. See InnerException for a complete description of the error. ---> 
 System.Web.HttpException: The control collection cannot be modified during DataBind, 
 Init, Load, PreRender or Unload phases.     at System.Web.UI.ControlCollection.Add(Control 
 child)     at Microsoft.SharePoint.Publishing.WebControls.WebPartRuntime.RegisterFeedUrl(String url, String type)    
 --- End of inner exception stack trace ---     at ....

When looking at the RegisterFeedUrl in .Net Reflector, we found out that the code actually accesses the Header property of the Page object that is being rendered and adds HtmlLink control to the collection. It gave us a hint that probably there is something wrong with the page and header objects. And – yes, we had left out the runat="server" part of the HTML and HEAD tags. So, this is the absolute minimum you must have:

<HTML runat="server">
    <HEAD runat="server">
....

.. and, of course, the name space references and other stuff you usually put in the HTML element tag.

Closed or open?

June 8th, 2008

No šiem abiem vismaz man mazliet skaidrāks kļuva, ko viņi saprot ar “open world approach”. Un, ka man to vajag.
http://www.cs.man.ac.uk/~drummond/presentations/OWA.pdf
http://www.betaversion.org/~stefano/linotype/news/91/

“Uz dullo”

April 2nd, 2008

Nesen gadījās izmantot dr.Viļņa Detlova lietoto izlozes metodi un te ir tās īss apraksts.

Dots

  • n elementu saraksts, no kura uz labu laimi jāizlozē viens ieraksts (piemēram, 25 cilvēku vārdi)
  • viens vai vairāki subjektīvi gadījuma skaitļu ģeneratori (piemēram, 2 cilvēki)
  • kalkulators (vēlami)

Izloze

  • sanumurē apskatāmā saraksta rindiņas sākot ar 0 un beidzot ar n-1
  • katrs skaitļu ģenerators iedomājas un paziņo citiem skaitli, kas par pārsniedz n (piemēram, viens dalībnieks paziņo skaitli 4842, otrs – 9222)
  • sasummē iegūto skaitļu kvadrātus, iegūstot kopīgu gadījuma lielumu K (K=48421^2+922103^2= 23444964+85045284= 108490248)
    • aprēķina (K mod n) un iegūst uzvarētāja kārtas numuru (108490248 mod 25 == 23, tātad uzvar priekšpēdējais dalībnieks)

Risinājuma pamatojums

  • Visiem saraksta elementiem ir līdzīga laba varbūtība kļūt par uzvarētājiem (neesmu mēģinājis pierādīt, bet šķiet labāka nekā ja mēģinātu izvēlēties skaitli no 0 līdz n-1)
  • Rezultāta izvēlē var iesaistīties pēc patikas daudz dalībnieku
  • Tā kā sākotnēji katrs dalībnieks nezina citu izvēlētos skaitļus, tas nevar iespaidot rezultātu ar subjektīvi izvēlētu gadījuma vērtību
  • Pat ja pēdējais dalībnieks redz iepriekšējo izvēlētos skaitļus, subjektīvi izvēlēta gadījuma skaitļa aprēķināšana ir apgrūtināta, jo skaitļi tiek kāpināti kvadrātā, tādēļ “prātā” jādarbojas ar nepatīkami lieliem skaitļiem.

Ko pasaule zina par Storm Worm?

February 28th, 2008

Ievadam – apnika lasīt par jauniem gadždetiem. Jāuzlabo LV blogu kultūra reportējot arī par citiem jaunumiem.

IEEE izdotā žurnāla “Computerfebruāra numurā ir ļoti interesants raksts par Storm Worm. IEEE bibliotēkas lasītājiem šis raksts ir pieejams arī tiešsaistē: “A Storm (Worm) Is Brewing”.

Īsumā – kopš 2006. gada rudens IT drošības pasaule ir iepazinusi jaunu ienaidnieku, kurš ticis pie vārda Storm, pirmo reizi īsti par sevi liekot manīt 2007. gada 19. janvārī, kad dienas laikā tika izsūtīts apmēram 20 reižu lielāks surogātpasta daudzums nekā citās dienās. Citi šī ienaidnieka nosaukumi ir Nuwar, Peacomm, Zhelatin. Pēdējais nosaukums vislabāk parāda šī kiber-ienaidnieka dabu, jo tieši mainīguma dēļ IT drošības kompānijām ir tik grūti izstrādāt pretlīdzekļus Storm-am.

Storm ir milzīgs attālināti kontrolējamu (“zombiju“) datoru tīkls, ar kura palīdzību tiek veikti kibernoziegumi, vienlaicīgi arī inficējot jaunus datorus un tos piesaistot storm tīklam. Drošības ekspertiem ir izdevies noteikt, ka tīkla darbības kontrolei tiek izmantoti austrumeiropā (tātad – arī Latvijā?) un Krievijā esošas IP adreses. Krievijas valdība atsakās sadarboties ar ASV spēkiem, lai likvidētu Storm tīklu.

Ir izteikti minējumi, ka 2007. gada pavasara DDoS uzbrukumi Igaunijas serveriem tikuši veikti no Storm tīkla. Tāpat Storm tiek pielietots naudas pelnīšanai, izsūtot surogātpastu, kas reklamē organizācijas, kuru akcijas pieder Storm īpašniekiem. Joe Stewart, SecureWorks pētnieks norāda, ka pastāv aizdomas, ka kāda Kanādas kompānija savulaik izīrējusi daļu tīkla resursu, lai izsūtītu surogātpastu.

Daži fakti par Storm:

  • Izplatās, izmantojot sociālās inženierijas ceļus. Izsūta e-pasta vēstules, ar tēmām “Milzīga vētra Eiropā”, “Nogalinājis 11 gados, 21 gada vecumā atkal brīvs un dodas nogalināt”, “Britu genocīds pret musulmaņiem”, “Krievu raķete notriekusi ASV satelītu”. Tāpat tiek izsūtītas e-pasta vēstules, kas satur saiti uz it kā Youtube esošām filmām. Vēl vienu klikšķi tālāk lietotāja neprasmīgi aizsargātais dators tiek inficēts ar Trojas zirgu.
  • Pēc datora inficēšanas sistēma var uzstādīt klaviatūras signālu pārķeršanas draiverus un šo informāciju pārsūtīt tīkla īpašniekiem. Protams, tiek izveidota “lūka”, caur kuru Storm īpašnieki var nodot komandas datoram
  • Programmatūra slēpjas. Tā instalē rootkit-us, lai izpildāmie faili nebūtu redzami datora lietotājam, tā modificē API, kas parāda aktīvos procesus, tā dzēš rīkus, kas ļautu identificēt Storm klātesamību.
  • Inficētie datori uzvedas gluži normāli un ir lietojami ikdienas darbam.
  • Decentralizēts – savstarpējai saziņai un izplatīšanai izmanto P2P tīklus, izmantojot savus protokolus un arī standarta rīkus kā ICQ un IRC
  • Izmanto t.s. fast flux principu, lai paslēptu web vietnes, kas satur inficējošo kodu. DNS ieraksti tiek mainīti ik pa dažām minūtēm, kas sevišķi apgrūtina izsekošanu.
  • Izplatīšanai vienlaicīgi izmanto tikai nelielu daļu no tīklā esošajiem datoriem, bet šī daļa regulāri mainās
  • Šifrē visu saziņu starp tīklā esošajiem datoriem, izmantojot vismaz 40 bitu atslēgas (simetriskās kriptosistēmās tas ir pietiekami daudz)
  • Izplatīšanās mehānisms tiek regulāri mainīts, tai skaitā mainot arī modificējot izpildāmo kodu līdz pat 10 reizēm stundā

UTF8 adreses

January 6th, 2008

Lietojot wikipediju, vienmēr meklēto vārdu rakstu uzreiz adresē (http://en.wikipedia.org/wiki/<vajadzīgais vārds>).

Līdzīgu pieeju mēģināju lietot arī latviešu wikipēdijā, bet secināju, ka vārdos ar latviešu diakritiskajiem simboliem tas nedarbojas. Piemēram, mēģinot atrast skaidrojumu vārdam “Māra”, atveras lapa “Mâra” (kur, protams, nekāda satura nav).

Kā noskaidroju, Firefox lietotāji to var labot ar slēdža Network.standard-url.encode-utf8 palīdzību. Uzstādot šo slēdzi uz “true”, Firefox sāk darboties atbilstoši RFC 3987 un visi nestandarta burti tiek kodēti ar URLencode.

Tas gan man nedarīja saprotamu, kāpēc pirmajā gadījumā teksts nokodējās uz
http://lv.wikipedia.org/wiki/M%C3%A2ra (Mâra)
bet otrajā uz
http://lv.wikipedia.org/wiki/M%C4%81ra (Māra)

Upd: Izskatās, ka šeit aprakstītā problēma nepastāv citos datoros kā tikai man mājās pieejamajos.

Tulkošanas makrosi

January 2nd, 2008

Divi Word makrosi, kas varētu noderēt tiem, kam nav instalēta Tildes vārdnīca, bet ir pieejams internets.

Lai lietotu, makrosu projektiem referencēs jāpieliek Microsoft XML (es liku V 6.0, bet derēs jebkurš). Pēc tam atliek uzbindēt klaviatūras saīsni. Piemēram, es ieliku Shift+Ctrl+Alt+E tulkojumam uz angļu valodu un Shift+Ctrl+Alt+L tulkojumam uz latviešu valodu. Pēc tam, kad vajag tulkojumu, iezīmējam tulkojamo vārdu un izpildām klaviatūras maģiju.

Uzskatu, ka SIA “Tilde” tiesības ar šo neesmu pārkāpis, jo esmu tikai vienkāršojis piekļuvi datiem, kas ir publiski pieejami.

Rezultāts izskatās šādi:

translator.png

Read the rest of this entry »