1

Really, how can I do it? This doesn't work:

List<object>[] myList= new List<object>[100](500);
3
  • both answers are good, but why don you need to do it ? A list by definition is something that will usually grow. If you want a predefined, why not use an array ? Commented Apr 14, 2016 at 23:51
  • Long story... I'm trying to absolutely minimize memory operations since that is my bottleneck. I try to fully utilize CPUs in a machine with 36 cores (AWS extra large instance). Commented Apr 15, 2016 at 0:06
  • so ... why don't you use arrays ?? :) Commented Apr 15, 2016 at 0:17

3 Answers 3

1

You could try something like this:

var array = Enumerable.Range(0,100).Select(n=>new List<object>(500)).ToArray();

Here we use the List<T> constructor with one argument, the List's capacity. Please have a look here.

Sign up to request clarification or add additional context in comments.

2 Comments

Will work, but ToArray doesn't know that it will always have 100 elements, so you'll create a bunch of unnecessary intermittent arrays based on default start small and double the size once limit reached heuristics.
@MarcinJuraszek good catch ! I might thought it a bit fast...Thanks for your comment.
1

Old style loop will do the trick:

List<object>[] myList= new List<object>[100];

for(int i = 0; i < 100; i++)
{
    myList[i] = new List<object>(500);
}

1 Comment

Thank you! This is a more understandable solution for someone like me. I actually tried the same thing with .capacity=500 inside the for. It didn't work...
1

You're not constructing the actual lists, just allocating space for storing references to them. You can only set the capacity when constructing the list objects.

You could wrap the array in another class and construct the lists lazily as they're needed:

class ListArray {
  private readonly List<object>[] _lists;
  private readonly int _capacity;

  public ListArray(int size, int capacity) {
    _lists = new List<object>[size];
    _capacity = capacity;
  }

  public List<object> this[int ix] {
    get { 
      if( _lists[ix] == null ) 
        _lists[ix] = new List<object>(capacity);
      return _lists[ix]
    }
  }
}

Then use it like

  var myList = new ListArray(100, 500);
  myList[0].Add(someObject);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.