I am making a page which pulls from the user's browser their preferred language, via the Request.UserLanguages....which returns a two letter code (ex. "en") or detailed code (ex. "en-GB").

I basically get the string of user languages (they are in order of preference) and store them in a string array. Then I use a loop to check if the language code in the first position of the string array is any of the codes for a certain language (another string array hard coded in).

Is there a better way to do this? I'm noticing increased load time and am worried additional languages will further slow the page load...

if (!IsPostBack)

    {   //Holds possible user languages preferences to check client machine against
        String[] compJapaneseLang = { "ja-jp","ja","jp","jpn","euc","shift-jis" };
    }

 //Get client machines langugage preferences                
        String[] userLang = Request.UserLanguages;

//Loop through variation of preferences from possible user langugaes

        for (int i = 0; i < compJapaneseLang.Length; i++)
        { 
                //IF JAPANESE
            if (userLang.GetValue(0).ToString().ToLowerInvariant().Equals(compJapaneseLang.GetValue(i).ToString().ToLowerInvariant()))


                cc.JapeneseObject();
        }

both compJapaneseLang and userLang are string arrays, but you treat them like they are not. Try changing your line 15 to

if (userLang[0] == compJapaneseLang[i])

There is no need to call ToString on a string, or use GetValue to index an array, or to call ToLowerInvariant when you know that they already are. Even with thousands of values this code should execute faster than you would notice.

Comments
Straightforward and clear answer. Thanks a ton!

both compJapaneseLang and userLang are string arrays, but you treat them like they are not. Try changing your line 15 to

if (userLang[0] == compJapaneseLang[i])

There is no need to call ToString on a string, or use GetValue to index an array, or to call ToLowerInvariant when you know that they already are. Even with thousands of values this code should execute faster than you would notice.

Great! Thank you! Certainly makes sense and is much more straightforward.


If you have any other suggestions as to an entirely different way to performing this (i.e. not using string arrays) that would also be greatly valuable.

Either way, I appreciate the help!

UPDATE: I just tested my program with the recommended change....very noticeable difference. I was looping through 5 or 6 languages and some have very long strings of possible language values....certainly a great tip.

Edited 5 Years Ago by bribissell: n/a

This article has been dead for over six months. Start a new discussion instead.