user374191
user374191

Reputation: 121

Performance Issue in for Loop?

Consider the following program,

     List<string> l_lstRawData = new List<string>();
     ........
     ........

Now the l_lstRawData is filled with data,for example,

    l_lstRawData[0] = "11111101101010................................0000011101010101";
    l_lstRawData[1] = "11111101111111...............................0000011101010101";
    l_lstRawData[2] = "11111101101010................................0000011101010101";
    l_lstRawData[3] = "11100001101010................................0000011101010101";
    l_lstRawData[4] = "11000101101010................................0000011101010101";
    l_lstRawData[5] = "11111101101010................................0000011101010101";

Now i want the result List l_lstResultData = new List();

    l_lstResultData [0] = "111111";
    l_lstResultData [1] = "111111";
    l_lstResultData [2] = "111101";
    l_lstResultData [3] = "111001";
    l_lstResultData [4] = "111001";

This is the code i am using, The Length of l_lstRawData is equal to each individual element in l_lstRawData

    string l_strTempData  = "";
    for(int l_nData;l_nData< l_lstRawData.Length;l_nData++)
    {
         l_strTempData  = "";
         for(int l_nItem = 0;l_nItem< l_lstRawData.Length;l_nItem++)
         {
             l_strTempData += l_lstRawData[**l_nData**].ToString();   
         }      
         l_lstResultData.Add(l_strTempData );
    }

It Takes long time since the each item of l_lstRawData Length is more than 60,000..... Is it possible using any other method?

If u have any queries plz revert back me.

Upvotes: 0

Views: 148

Answers (3)

Robert Seder
Robert Seder

Reputation: 1420

Use StringBuilder! Strings are immuatable (they don't change). Every time you concatenate a string, the run-time creates a NEW string with the new contents, and gives the older version of garbage collection. When you do this in loop, this can become a significant problem. Use StringBuilder instead and you'll see a dramatic difference.

Upvotes: 0

Pavel Radzivilovsky
Pavel Radzivilovsky

Reputation: 19104

You could start by using stringbuilder instead of string concatenation.

Second, what you are doing in the loop can be done with a very fast substring method instead.

Upvotes: 1

Joel Martinez
Joel Martinez

Reputation: 47749

Oh boy, yeah, string concatenation is really slow. You should consider using the StringBuilder class

http://msdn.microsoft.com/en-us/library/2839d5h5%28VS.71%29.aspx

Upvotes: 6

Related Questions