Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- static class Program
- {
- static Random random = new Random();
- [STAThread]
- static void Main()
- {
- int loopTimes = 1000;
- int listSize = 10000;
- Console.WriteLine("Testing performance of filling a list to {0} items {1} times, discarding 1/2 of items after every fill!", listSize, loopTimes);
- Console.WriteLine();
- Random r = new Random();
- List<int> oldList = new List<int>();
- List<int> newList = new List<int>();
- Stopwatch watch = new Stopwatch();
- watch.Start();
- OldListTimes(loopTimes, listSize, oldList);
- watch.Stop();
- Console.WriteLine("Old list: {0}ms", watch.ElapsedMilliseconds);
- watch.Restart();
- NewListTimes(loopTimes, listSize, oldList);
- watch.Stop();
- Console.WriteLine("New list: {0}ms", watch.ElapsedMilliseconds);
- Console.WriteLine("DONE");
- Console.ReadKey();
- }
- private static void OldListTimes(int loopTimes, int listSize, List<int> list)
- {
- for (var fillLoop = 0; fillLoop < loopTimes; fillLoop++)
- {
- for (int i = list.Count; i < listSize; i++)
- AddToSortedList(list, random.Next(100000));
- //list.Sort();
- list.RemoveRange(listSize / 2, listSize / 2);
- }
- }
- private static void NewListTimes(int loopTimes, int listSize, List<int> list)
- {
- for (var fillLoop = 0; fillLoop < loopTimes; fillLoop++)
- {
- for (int i = list.Count; i < listSize; i++)
- list.Add(random.Next(100000));
- list.Sort();
- list.RemoveRange(listSize / 2, listSize / 2);
- }
- }
- private static void AddToSortedList(List<int> sortedList, int item)
- {
- int min = 0;
- int max = sortedList.Count;
- int index = 0;
- while (min < max)
- {
- index = (min + max) / 2;
- if (item < sortedList[index])
- {
- min = index + 1;
- index = min;
- }
- else
- {
- if (item > sortedList[index])
- {
- max = index;
- index = max;
- }
- else
- break;
- }
- }
- sortedList.Insert(index, item);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement