We cannot create a HashSet with a default capacity! To prevent resizing during runtime we will add elements to the hashset then clear it so it will have enough space internally to do it's operations without the need to re-size. - CSharp System

CSharp examples for System:DateTime

Description

We cannot create a HashSet with a default capacity! To prevent resizing during runtime we will add elements to the hashset then clear it so it will have enough space internally to do it's operations without the need to re-size.

Demo Code


using System.Linq;
using System;//from   ww w .  j  a  v a2s  .  c  o  m
using System.Collections.Generic;
using System.Collections;
using UnityEngine;

public class Main{
        /// <summary>
        /// We cannot create a HashSet with a default capacity! To prevent
        /// resizing during runtime we will add elements to the hashset then clear
        /// it so it will have enough space internally to do it's operations without 
        /// the need to re-size. 
        /// </summary>
        public static void PreallocateCapacity(this HashSet<int> toPopulate, int capacity)
        {
            if (toPopulate == null)
            {
                return;
            }

            capacity = Mathf.Max(0, capacity);

            for (int i = 0; i < capacity; i++)
            {
                toPopulate.Add(i);
            }

            toPopulate.Clear();
        }
}

Related Tutorials