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();
        }

Recommended Answers

All 2 Replies

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.

commented: Straightforward and clear answer. Thanks a ton! +0

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.