Member 8491154 Ответов: 5

Что лучше? array, ArrayList или List (с точки зрения производительности и скорости)


Мне нужна быстрая скорость обработки моей страницы. Какой из вышеперечисленных вариантов предпочтительнее? Поддержка с уважительной причиной.

Edit: For eg:

string str = "a,b,c"; //Count of the number of elements in str is not fixed
string[] arr = str.Split(',');

ArrayList al = new ArrayList();
al.Add(str.Split(','));


Какой из них дает более быстрые результаты?

Sunny_Kumar_

зависит от того, какую обработку вам нужно сделать...пожалуйста, раскройте некоторые детали предмета, чтобы мы могли иметь лучшую картину, чтобы помочь вам :)

Member 8491154

я опубликовал пример

5 Ответов

Рейтинг:
36

Prasad_Kulkarni

Емкость Array крепиться.
Где как, ArrayList может динамически увеличивать и уменьшать размер.

Один Array это коллекция похожих предметов.
Где как, ArrayList может содержать предметы разных типов.

Массив находится в системном пространстве имен.
Где as, ArrayList находится в системе.Пространство имен коллекций.

Один Array может иметь несколько измерений.
Где как, ArrayList всегда имеет ровно одно измерение.

Мы можем установить нижнюю границу Array.
Где как, от нижней границы ArrayList всегда равен нулю.

Array это быстрее и это потому что ArrayList использует фиксированный объем массива.
Однако когда вы добавляете элемент в ArrayList и она переливается через край. Он создает новое Array и копирует каждый элемент из старого в новый.
Вы почувствуете это, только если будете часто добавлять.

С момента добавления от ArrayList это O (n) и добавление к Array Это O (1).

Однако потому что ArrayList использует Array быстрее искать в нем O(1), чем в обычных списках O(n).

Список по массивам.
Если вы не превысите емкость, она будет такой же быстрой, как массив.
Лучшее управление и гораздо более простой способ делать вещи.

Обратиться:
Типы коллекций ArrayList и List[^]


Member 8491154

Я слышал, что ArrayList устарел. Это правда?

Рейтинг:
1
Рейтинг:
1

db7uk

Самая высокоэффективная коллекция - это хэш-таблица. Массивы, Arraylists и списки - это коллекции объектов, что означает, что поиск их снова происходит медленнее, чем использование ключа в оптимизированной коллекции, такой как hashtable.


Рейтинг:
1

Member 12928891

// The main thing I can add to this is that a LINQ query is almost always faster than a loop such as a foreach, etc. Here are a couple of prime examples in optimized code form.

// Try to use queries rather than loops.

    /// <summary> This one accepts the Collection of Dictionaries for
    /// ViewAllAssociations(); Has it's own special Size & Location Settings.
    /// It directly calls the Mother Method of them all below this one.
    /// NOTE: "var x = ..." below does a ton of work,
    /// & faster because instead of a loop it's a LINQ query!
    /// 
    /// <param name="listOfLists">
    private static void DisplayResults
      (IEnumerable<Dictionary<string, string>> listOfLists)
    {
      #region was
      //var i = 0;
      //var text = "";
      //foreach (var dic in listOfLists)
      //{
      ////  if (i == reportsListBox.Items.Count) break;
      //  text += GetDisplayString(dic, reportsListBox.Items[i++].ToString());
      //}
      #endregion was
      var i = 0;
      var
        x = listOfLists.Aggregate("", (current, dic) => current +
        GetDisplayString(dic, OPS.Default.reportsListBoxItems[i++]));

      const string t = "";
      var s = AUS.Default.OMA_D4_S;
      var l = AUS.Default.OMA_D4_L;
        DisplayResults(x, t, ref s, ref l);
      AUS.Default.OMA_D4_S = s;
      AUS.Default.OMA_D4_L = l;
      AUS.Default.Save();
    }

    /// <summary> This overload is where all end up.
    /// It allows for total flexibility of usages for all args.
    /// While providing critical defaults to reduce duplicity.
    /// if title is empty it defaults to:
    /// "Folder Associations Information:"
    /// 
    /// <param name="x">
    /// <param name="t">
    /// <param name="s">
    /// <param name="l">
    private static void DisplayResults
      (string x, string t, ref Size s, ref Point l)
    {
      if (string.IsNullOrEmpty(t)) t =
        "Folder Associations Information:";
      using (var f = new ShowMeForm(x, t))
      {
        f.Size     = s;
        f.Location = l;
          f.ShowDialog();
        l = f.Location;
        s = f.Size;
      }
    }

    /// <summary> This was split out so it can be used by both
    /// the View2Associations and the ViewAllAssociations: v4.7.3.75
    /// Added the string dir arg to the sig to interface it with both.
    /// 
    /// <param name="dic">
    /// <param name="dir">
    /// <returns>
    private static string GetDisplayString
      (Dictionary<string, string> dic, string dir)
    { // Sweet! Great integration.
      #region Was
      //foreach (var pair in list)
      //{
      //  // Concatenate the text string and show it.
      //  text += "The Data Folder:\n" + pair.Key +
      //    "\n\nWhich is set to the Data file: \n" +
      //    pair.Value + "\n\n";
      //}
      #endregion Was
      string
        title = string.Format("\nResults for: {0}\n\n", dir),
        text  = title +
          "The following currently use this Reports Folder:\n\n";
      return
        dic.Aggregate(text, (current, pair) => current +
          ("The Data Folder:\n" + pair.Key +
            "\n\nWhich is set to the Data file: \n" +
              pair.Value + "\n\n"));
    }
// Whereever it says .Aggregate here are good examples and it can be many Types.

// Take the first one:
// var x = listOfLists.Aggregate blah blah...
// Think for a minute what that is doing, it's iterating through a Collection of Dictionary Collections and getting the appropriate string for each and very very rapidly and efficiently!
// Follow the code path through that down to this other one above and you will see what I mean. From the Collection of Dictionaries down to this does a LOT. 


[no name]

Если вы собираетесь продолжать без необходимости воскрешать древние уже отвеченные "вопросы", несмотря на то, что вам сказали не делать этого, вы могли бы, по крайней мере, предоставить точную информацию.

Рейтинг:
0

Jim Jos

Похоже, там маленький мир.. Я думаю, что вы задавали тот же вопрос и на следующих сайтах...

http://forums.asp.net/p/1808968/5004003.aspx/1?Which+is+better+array+ArrayList+or+List+T+in+terms+of+performance+and+speed+


http://stackoverflow.com/questions/10815565/which-is-better-array-arraylist-or-listt-in-terms-of-performance-and-speed


Массив, несомненно, быстрее, чем два других. List< t & gt; гораздо сложнее, чем array / arraylist.. Arraylist находится между смешиванием скорости массива и удобством List< t>