SlideShare uma empresa Scribd logo
1 de 40
Collections and Generics
● Data structure that stores multiple
objects (eg: a list of users)
● All objects of the same or common type
(eg: same Class, Interface, base class...)
● All are Enumerable (foreach, LINQ)
● namespace:
System.Collections.Generic
*System.Array
What are Collections?
● Ability to pass a Class as a parameter to
Another Class or Method.
Ex:
//Generic Collections of users (C#)
Queue<User> userQueue = new Queue<User>();
Stack<User> userStack = new Stack<User>();
List<User> userList = new List<User>();
//System.Array, Technically Not Generic but allowed
User[] users = new User[50];
What is Generics?
● Arrays
○Stored in Adjacent Memory Block
○Declared with Limited number of items
○Fast, Performance Efficient :)
○Low Flexibility :(
○Array, Stack, Queue, List, Dictionary, SortedList
● Multidimensional Linked List
○Stored and distributed arbitrarily in Memory
○Limited only by the amount of memory available
○Memory Efficient, High Flexibility :)
○Slow to Search :(
○LinkedList is a Linked List
○SortedDictionary uses a Binary Search Tree
Types of ‘Collections’ (All Platforms)
● Non-generic
○The ‘old’ type of collections
○each item in Collection is of type Object
○Must Cast (Box/Unbox) each item
○Windows Store BANNED!
○DO NOT USE!!! >:-(
● Generic
○Items of specific Type (using Generics)
○No Boxing/Unboxing or casting required
○Ok to use. Knock yourself out! :-)
Category of Collections (C#)
● O(1): same time allways (excelent!)
● O(logN): disproportionatly favorable (pretty good!)
● O(N): linear, proportional (ok, I guess...)
● O(NlogN):disproportionatly unfavorable (could be worse)
● O(N2): exponential (bad)
● O(N3): exponential (NOT GOOD AT ALL!!!)
before we begin... Big-O Summary!
Big-O Notation is a mathematical notation that measures the
performance scalability of an algorithm.
In context of Collections, it is usually Time vs Amount of Data.
Performance on Collections operations depends on Operation
and Type of Collection
● O(1): 1 ms
● O(logN): 20 ms
● O(N): 1,000,000 ms (16 min)
● O(NlogN): 20,000,000 ms (5 h 32 min)
● O(N2): 1,000,0002 ms (31.7 years!)
● O(N3): 1,000,0003 ms (31 MILLION YEARS!!!)
Big-O in Perspective (thought experiment)
Imagine we develop in an old computer where an operation to a
collection item cost 1 ms (one millisecond).
Imagine the old computer has an absurd amount of RAM and we
are operating on a Collection with 1,000,000 (1 million) records.
Generic Collection Types
ICollection
IList IDictionary Queue
DictionaryList
Stack
LinkedList
SortedList
System.Array
SortedDictionary
IEnumerable
ReadOnlyCollection
ObservableCollection
ImmutableList
IEnumerable<T>
● Iteration Behavior
● GetEnumerator()
● Enumerator allows you to navigate
Collection from Start to Finish
● LINQ
● If implemented, it is a Collection
● No Manipulation available
● Can’t count!
ICollection<T>
● Container Behavior
● Has Manipulation
● Count(), Add(), Remove(), Clear()
● is IEnumerable<T>
IList<T>
● Array Behavior
● Access using [index]
● More Manipulation: AddRange(),
RemoveRange(), Insert(), Sort()...
● is ICollection<T>
IDictionary<TKey, TValue>
● Map Behavior
● Access using [TKey]
● Manipulation! (Add, Remove, Clear…)
● is ICollection<KeyValuePair<TKey, TValue>>
Generic Collection Types
ICollection
IList IDictionary Queue
DictionaryList
Stack
LinkedList
SortedList
System.Array
SortedDictionary
IEnumerable
ReadOnlyCollection
ObservableCollection
ImmutableList
● Stack<T>
● Queue<T>
● List<T>
● Dictionary<TKey, TValue>
● LinkedList<T>
● SortedList<T>
● SortedDictionary<TKey, TValue>
● ReadOnlyCollection<T>
● ObservableCollection<T>
● ImmutableList<T>
● *System.Array
Generic Collection Types
Note to Self: Remember
that there is code for
each of these...
● LIFO: Last In, First Out
● Push(item) to Add at the Top
● Pop() to Access/Remove from Top
● Eg: A ‘stack’ of Books
● Eg: Cars parked in a narrow
corridor
● No Index*
Stack<T> (Pila)
● FIFO: First In, First Out
● Enqueue(item) to Add/Push to Back
● Dequeue() to Access/Remove from Front
● Example: A line in a Bank
● No Index
Queue<T> (Cola)
● Queue and Stack are Lightning Fast!
● Are a reflection of the Limitations of
Digital Computing
● All Operations are O(1)*
● It’s called CallStack for a reason…
● It’s called MessageQueue for a reason...
● Use if you dont need Searching
Why use Queue<T> or Stack<T>?
● Has index for searching
● Reserves more Memory than it needs
● Read, Write, Add are O(1)*
● Insert and Remove are O(N)
● Use if you benefit from index access
List<T>
● Maps a TKey object with a TValue object
● Hashtable
● Reserves more Memory than it needs
● Read, Write, Add, Remove are O(1)*
● Use if you need to search objects
quickly using a data key. (id, code)
Dictionary<TKey, TValue>
● Capacity is the amount of Items a
collection can hold before having to
reallocate itself
● Capacity != Count
● List<T>, Queue<T>, Stack<T>,
Dictionary<TKey, TValue>
● When O(1) operation requires capacity
to change (Add), cost becomes O(N)
...About Capacity
● Only occupies the memory it needs
● Read, Write, Add, Remove is O(1)
● No Index, searching is O(N)
● Use if you need to access all items
● Avoid using if you need to search by
index or key
LinkedList<T>
● TValue is sorted automatically by TKey
● Read, Write are O(logN)
● Add, Remove are O(N)
● Less Memory Footprint than Alternative
● Slower than Alternative
SortedList<TKey, TValue>
● TValue is sorted automatically by TKey
● Self Balancing Binary Search Tree
● Read, Write, Add, Remove are O(logN)*
● Use if you need all items sorted
● Use if you want to search using Key
SortedDictionary<TKey, TValue>
Balanced vs Unbalanced Binary Search Tree
SortedDictionary<TKey, TValue>
● Read Only Wrapper
● Receives List<T> as parameter
● Source list cannot be modified through
wrapper
● Source list can be modified directly
● Modifications are reflected
● Not Thread-safe, Liability
● Use it when you want to prevent
modification under certain contexts.
ReadOnlyCollection<T>
● Has events for when elements in
collection change:
○CollectionChanged
● Think of the event as a Triggers (SQL)
● Use if you need to trigger events when
elements are added/removed or
properties changed
ObservableCollection<T>
● Cannot be Modified
● Thread-Safe
● Use if you want to access list in multiple
threads, but not write or change
ImmutableList<T>
● Primitive Type
● Succeded by List<T>
● Technically not Generic but Allowed
● Marginally better performance
● Can’t change size
● Use it if you really need maximum bare-metal
hardware performance
//Example of Array with 10 users
User[] users = new User[10];
//Example of TWO DIMENSIONAL Array with 10x10 users
User[][] users = new User[10][];
for (int i=0;i<10;i++) users[i] = new User[10];
What about System.Array?
● If you don’t know, then just use List<T>
● Only use LinkedList<T> if:
○need low memory footprint
○no need for index or key
○loop over all items
● As Hardware becomes more powerful,
List<T> becomes the better option
List<T> vs LinkedList<T>
● Use ImmutableList<T> if:
○Multithreading
● ReadOnlyCollection<T> is a wrapper, so
it has low memory footprint
● ImmutableList<T> is a copy, so it has a
high memory footprint
ReadOnlyCollection<T> vs
ImmutableList<T>
● Performance benefits only apply if using
Index (Array, List) or Key (Dictionary)
● Searching using LINQ on a Collection
defeats purpose of index/key
● LINQ search performance is O(N)
About Searching and LINQ
● Using LINQ over Sort has no
performance impact
● Sorting any type of Collections has a
cost of O(NlogN) (QuickSort, InsertSort,
MergeSort...)
About Sorting
● Default Collection types not Thread-Safe
(you can only use them in one thread)
● Thread-Safe version of Collections are:
○ConcurrentQueue (Queue)
○ConcurrentStack (Stack)
○ConcurrentDictionary (Dictionary)
○ConcurrentBag
○*System.Collections.Concurrent
Collections and Multithreading
● Immutables can also be used, but they
are read only
● Other Immutable Collections:
○ImmutableQueue (Queue)
○ImmutableStack (Stack)
○ImmutableList (List)
○ImmutableDictionary (Dictionary)
○*System.Collections.Immutable
Collections and Multithreading
● Finally, Worst Case, if you need to, you
can just use lock
Collections and Multithreading
void method(List<User> users) {
lock(users) {
//Do your multi threading stuff here
users.Add(new User { … });
}
}
● Remote communications and data
transmission performance: O(N)
● Make sure the Database does all the
hard work (filtering, sorting, joining)
● Think of Scalability
About Collections and Databases
● When exposing collections in WebAPI’s,
Microsoft recommends returning
interfaces rather than implementations.
○IEnumerable
○ICollection
○IList, IDictionary…
● Return Empty Collection
● Don’t return NULL
About Collections and Web API
● O(1): Most simple operations
● O(logN): Binary Searching
● O(N): Linear Searching, LINQ
● O(NlogN): Sorting
● O(N2): Nested loops
(Ex: for in a for)
Common Big-O Calculations
You are now a Collection expert!... sort of...
Questions?
...Aaaaaaaand… THAT’S IT!
Thank you!
Marco Hernandez
mhernandez@growthaccelerationpartners.com
Code:
https://github.com/marcohern/CollectionsAndGenerics

Mais conteúdo relacionado

Mais procurados

Stl (standard template library)
Stl (standard template library)Stl (standard template library)
Stl (standard template library)
Hemant Jain
 

Mais procurados (20)

How to choose best containers in STL (C++)
How to choose best containers in STL (C++)How to choose best containers in STL (C++)
How to choose best containers in STL (C++)
 
Stl Containers
Stl ContainersStl Containers
Stl Containers
 
Stl (standard template library)
Stl (standard template library)Stl (standard template library)
Stl (standard template library)
 
Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template Library
 
STL in C++
STL in C++STL in C++
STL in C++
 
Sets
SetsSets
Sets
 
Intro to JavaScript - Week 4: Object and Array
Intro to JavaScript - Week 4: Object and ArrayIntro to JavaScript - Week 4: Object and Array
Intro to JavaScript - Week 4: Object and Array
 
Prototypes in Pharo
Prototypes in PharoPrototypes in Pharo
Prototypes in Pharo
 
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...
 
Processing data with Python, using standard library modules you (probably) ne...
Processing data with Python, using standard library modules you (probably) ne...Processing data with Python, using standard library modules you (probably) ne...
Processing data with Python, using standard library modules you (probably) ne...
 
Maps
MapsMaps
Maps
 
Few simple-type-tricks in scala
Few simple-type-tricks in scalaFew simple-type-tricks in scala
Few simple-type-tricks in scala
 
An Introduction to the C++ Standard Library
An Introduction to the C++ Standard LibraryAn Introduction to the C++ Standard Library
An Introduction to the C++ Standard Library
 
Ch02
Ch02Ch02
Ch02
 
Session 17 - Collections - Lists, Sets
Session 17 - Collections - Lists, SetsSession 17 - Collections - Lists, Sets
Session 17 - Collections - Lists, Sets
 
Session 14 - Object Class
Session 14 - Object ClassSession 14 - Object Class
Session 14 - Object Class
 
Session 15 - Collections - Array List
Session 15 - Collections - Array ListSession 15 - Collections - Array List
Session 15 - Collections - Array List
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Json processing
Json processingJson processing
Json processing
 
Introductory Clojure Presentation
Introductory Clojure PresentationIntroductory Clojure Presentation
Introductory Clojure Presentation
 

Semelhante a Collections and generics

Semelhante a Collections and generics (20)

CSharp for Unity - Day 1
CSharp for Unity - Day 1CSharp for Unity - Day 1
CSharp for Unity - Day 1
 
Ledingkart Meetup #2: Scaling Search @Lendingkart
Ledingkart Meetup #2: Scaling Search @LendingkartLedingkart Meetup #2: Scaling Search @Lendingkart
Ledingkart Meetup #2: Scaling Search @Lendingkart
 
Data efficiency on BEAM - Choose the right data representation by Dmytro Lyto...
Data efficiency on BEAM - Choose the right data representation by Dmytro Lyto...Data efficiency on BEAM - Choose the right data representation by Dmytro Lyto...
Data efficiency on BEAM - Choose the right data representation by Dmytro Lyto...
 
Building a Unified Logging Layer with Fluentd, Elasticsearch and Kibana
Building a Unified Logging Layer with Fluentd, Elasticsearch and KibanaBuilding a Unified Logging Layer with Fluentd, Elasticsearch and Kibana
Building a Unified Logging Layer with Fluentd, Elasticsearch and Kibana
 
Talk on Standard Template Library
Talk on Standard Template LibraryTalk on Standard Template Library
Talk on Standard Template Library
 
Meet the-other-elephant
Meet the-other-elephantMeet the-other-elephant
Meet the-other-elephant
 
Rohan Sharma MOOC Course Report (1).pptx
Rohan Sharma MOOC Course Report (1).pptxRohan Sharma MOOC Course Report (1).pptx
Rohan Sharma MOOC Course Report (1).pptx
 
The Parquet Format and Performance Optimization Opportunities
The Parquet Format and Performance Optimization OpportunitiesThe Parquet Format and Performance Optimization Opportunities
The Parquet Format and Performance Optimization Opportunities
 
Task and Data Parallelism
Task and Data ParallelismTask and Data Parallelism
Task and Data Parallelism
 
New c sharp3_features_(linq)_part_iii
New c sharp3_features_(linq)_part_iiiNew c sharp3_features_(linq)_part_iii
New c sharp3_features_(linq)_part_iii
 
Programming for Performance
Programming for PerformanceProgramming for Performance
Programming for Performance
 
Data Infra Meetup | ByteDance's Native Parquet Reader
Data Infra Meetup | ByteDance's Native Parquet ReaderData Infra Meetup | ByteDance's Native Parquet Reader
Data Infra Meetup | ByteDance's Native Parquet Reader
 
Manticore 6.pdf
Manticore 6.pdfManticore 6.pdf
Manticore 6.pdf
 
Mongo nyc nyt + mongodb
Mongo nyc nyt + mongodbMongo nyc nyt + mongodb
Mongo nyc nyt + mongodb
 
14. collections
14. collections14. collections
14. collections
 
L1 - Recap.pdf
L1 - Recap.pdfL1 - Recap.pdf
L1 - Recap.pdf
 
Elasticsearch Architechture
Elasticsearch ArchitechtureElasticsearch Architechture
Elasticsearch Architechture
 
Discovering python search engines
Discovering python search enginesDiscovering python search engines
Discovering python search engines
 
lect 2-DS ALGO(online).pdf
lect 2-DS  ALGO(online).pdflect 2-DS  ALGO(online).pdf
lect 2-DS ALGO(online).pdf
 
Algorithms__Data_Structures_-_iCSC_2018.pptx
Algorithms__Data_Structures_-_iCSC_2018.pptxAlgorithms__Data_Structures_-_iCSC_2018.pptx
Algorithms__Data_Structures_-_iCSC_2018.pptx
 

Mais de Miguel Angel Teheran Garcia

Mais de Miguel Angel Teheran Garcia (20)

Pruebas Automatizadas con PlayWright sobre nuestras Google Cloud Functions
Pruebas Automatizadas con PlayWright sobre nuestras Google Cloud FunctionsPruebas Automatizadas con PlayWright sobre nuestras Google Cloud Functions
Pruebas Automatizadas con PlayWright sobre nuestras Google Cloud Functions
 
PlayWright, Cypress, Selenium Cual es la mejor opción para desarrolladores Ja...
PlayWright, Cypress, Selenium Cual es la mejor opción para desarrolladores Ja...PlayWright, Cypress, Selenium Cual es la mejor opción para desarrolladores Ja...
PlayWright, Cypress, Selenium Cual es la mejor opción para desarrolladores Ja...
 
Introduction to Blazor Hybrid
Introduction to Blazor HybridIntroduction to Blazor Hybrid
Introduction to Blazor Hybrid
 
La historia de api-colombia
La historia de api-colombiaLa historia de api-colombia
La historia de api-colombia
 
DevFest 2022 - El Arte de escribir sobre programacion.pptx
DevFest 2022 - El Arte de escribir sobre programacion.pptxDevFest 2022 - El Arte de escribir sobre programacion.pptx
DevFest 2022 - El Arte de escribir sobre programacion.pptx
 
RoadMap y herramientas de Azure DevOps que debes conocer
RoadMap y herramientas de Azure DevOps que debes conocerRoadMap y herramientas de Azure DevOps que debes conocer
RoadMap y herramientas de Azure DevOps que debes conocer
 
Taller de TDD con .NET y xUnit
Taller de TDD con .NET y xUnitTaller de TDD con .NET y xUnit
Taller de TDD con .NET y xUnit
 
Introduction to OpenTelemetry in .NET
Introduction to OpenTelemetry in .NETIntroduction to OpenTelemetry in .NET
Introduction to OpenTelemetry in .NET
 
PRISM con MAUI
PRISM con MAUIPRISM con MAUI
PRISM con MAUI
 
.NET MAUI Offline first
.NET MAUI Offline first .NET MAUI Offline first
.NET MAUI Offline first
 
MAUIConf - Adios Net Maui Essentials Bienvenida Integración de Plataforma
MAUIConf - Adios Net Maui Essentials Bienvenida Integración de PlataformaMAUIConf - Adios Net Maui Essentials Bienvenida Integración de Plataforma
MAUIConf - Adios Net Maui Essentials Bienvenida Integración de Plataforma
 
Servicios Nativos MAUI
Servicios Nativos MAUIServicios Nativos MAUI
Servicios Nativos MAUI
 
Aplicaciones para MacOS con .NET MAUI
Aplicaciones para MacOS con .NET MAUIAplicaciones para MacOS con .NET MAUI
Aplicaciones para MacOS con .NET MAUI
 
Primero pasos con Visual Studio for MAC
Primero pasos con Visual Studio for MACPrimero pasos con Visual Studio for MAC
Primero pasos con Visual Studio for MAC
 
Aplicaciones con web con Blazor + MudBlazor
Aplicaciones con web con Blazor + MudBlazorAplicaciones con web con Blazor + MudBlazor
Aplicaciones con web con Blazor + MudBlazor
 
Building Web Applications with Blazor and MudBlazor
Building Web Applications with Blazor and MudBlazorBuilding Web Applications with Blazor and MudBlazor
Building Web Applications with Blazor and MudBlazor
 
Tips para una entrevista Tech Exitosa
Tips para una entrevista Tech ExitosaTips para una entrevista Tech Exitosa
Tips para una entrevista Tech Exitosa
 
Metaverso y Microsoft Mesh
Metaverso y Microsoft MeshMetaverso y Microsoft Mesh
Metaverso y Microsoft Mesh
 
Mejoras en Blazor con .NET 6
Mejoras en Blazor con .NET 6Mejoras en Blazor con .NET 6
Mejoras en Blazor con .NET 6
 
Apis with dotnet postgreSQL and Apsaradb
Apis with dotnet postgreSQL and ApsaradbApis with dotnet postgreSQL and Apsaradb
Apis with dotnet postgreSQL and Apsaradb
 

Último

Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
chiefasafspells
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 

Último (20)

WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaS
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 

Collections and generics

  • 2. ● Data structure that stores multiple objects (eg: a list of users) ● All objects of the same or common type (eg: same Class, Interface, base class...) ● All are Enumerable (foreach, LINQ) ● namespace: System.Collections.Generic *System.Array What are Collections?
  • 3. ● Ability to pass a Class as a parameter to Another Class or Method. Ex: //Generic Collections of users (C#) Queue<User> userQueue = new Queue<User>(); Stack<User> userStack = new Stack<User>(); List<User> userList = new List<User>(); //System.Array, Technically Not Generic but allowed User[] users = new User[50]; What is Generics?
  • 4. ● Arrays ○Stored in Adjacent Memory Block ○Declared with Limited number of items ○Fast, Performance Efficient :) ○Low Flexibility :( ○Array, Stack, Queue, List, Dictionary, SortedList ● Multidimensional Linked List ○Stored and distributed arbitrarily in Memory ○Limited only by the amount of memory available ○Memory Efficient, High Flexibility :) ○Slow to Search :( ○LinkedList is a Linked List ○SortedDictionary uses a Binary Search Tree Types of ‘Collections’ (All Platforms)
  • 5. ● Non-generic ○The ‘old’ type of collections ○each item in Collection is of type Object ○Must Cast (Box/Unbox) each item ○Windows Store BANNED! ○DO NOT USE!!! >:-( ● Generic ○Items of specific Type (using Generics) ○No Boxing/Unboxing or casting required ○Ok to use. Knock yourself out! :-) Category of Collections (C#)
  • 6. ● O(1): same time allways (excelent!) ● O(logN): disproportionatly favorable (pretty good!) ● O(N): linear, proportional (ok, I guess...) ● O(NlogN):disproportionatly unfavorable (could be worse) ● O(N2): exponential (bad) ● O(N3): exponential (NOT GOOD AT ALL!!!) before we begin... Big-O Summary! Big-O Notation is a mathematical notation that measures the performance scalability of an algorithm. In context of Collections, it is usually Time vs Amount of Data. Performance on Collections operations depends on Operation and Type of Collection
  • 7. ● O(1): 1 ms ● O(logN): 20 ms ● O(N): 1,000,000 ms (16 min) ● O(NlogN): 20,000,000 ms (5 h 32 min) ● O(N2): 1,000,0002 ms (31.7 years!) ● O(N3): 1,000,0003 ms (31 MILLION YEARS!!!) Big-O in Perspective (thought experiment) Imagine we develop in an old computer where an operation to a collection item cost 1 ms (one millisecond). Imagine the old computer has an absurd amount of RAM and we are operating on a Collection with 1,000,000 (1 million) records.
  • 8. Generic Collection Types ICollection IList IDictionary Queue DictionaryList Stack LinkedList SortedList System.Array SortedDictionary IEnumerable ReadOnlyCollection ObservableCollection ImmutableList
  • 9. IEnumerable<T> ● Iteration Behavior ● GetEnumerator() ● Enumerator allows you to navigate Collection from Start to Finish ● LINQ ● If implemented, it is a Collection ● No Manipulation available ● Can’t count!
  • 10. ICollection<T> ● Container Behavior ● Has Manipulation ● Count(), Add(), Remove(), Clear() ● is IEnumerable<T>
  • 11. IList<T> ● Array Behavior ● Access using [index] ● More Manipulation: AddRange(), RemoveRange(), Insert(), Sort()... ● is ICollection<T>
  • 12. IDictionary<TKey, TValue> ● Map Behavior ● Access using [TKey] ● Manipulation! (Add, Remove, Clear…) ● is ICollection<KeyValuePair<TKey, TValue>>
  • 13. Generic Collection Types ICollection IList IDictionary Queue DictionaryList Stack LinkedList SortedList System.Array SortedDictionary IEnumerable ReadOnlyCollection ObservableCollection ImmutableList
  • 14. ● Stack<T> ● Queue<T> ● List<T> ● Dictionary<TKey, TValue> ● LinkedList<T> ● SortedList<T> ● SortedDictionary<TKey, TValue> ● ReadOnlyCollection<T> ● ObservableCollection<T> ● ImmutableList<T> ● *System.Array Generic Collection Types Note to Self: Remember that there is code for each of these...
  • 15. ● LIFO: Last In, First Out ● Push(item) to Add at the Top ● Pop() to Access/Remove from Top ● Eg: A ‘stack’ of Books ● Eg: Cars parked in a narrow corridor ● No Index* Stack<T> (Pila)
  • 16. ● FIFO: First In, First Out ● Enqueue(item) to Add/Push to Back ● Dequeue() to Access/Remove from Front ● Example: A line in a Bank ● No Index Queue<T> (Cola)
  • 17. ● Queue and Stack are Lightning Fast! ● Are a reflection of the Limitations of Digital Computing ● All Operations are O(1)* ● It’s called CallStack for a reason… ● It’s called MessageQueue for a reason... ● Use if you dont need Searching Why use Queue<T> or Stack<T>?
  • 18. ● Has index for searching ● Reserves more Memory than it needs ● Read, Write, Add are O(1)* ● Insert and Remove are O(N) ● Use if you benefit from index access List<T>
  • 19. ● Maps a TKey object with a TValue object ● Hashtable ● Reserves more Memory than it needs ● Read, Write, Add, Remove are O(1)* ● Use if you need to search objects quickly using a data key. (id, code) Dictionary<TKey, TValue>
  • 20. ● Capacity is the amount of Items a collection can hold before having to reallocate itself ● Capacity != Count ● List<T>, Queue<T>, Stack<T>, Dictionary<TKey, TValue> ● When O(1) operation requires capacity to change (Add), cost becomes O(N) ...About Capacity
  • 21. ● Only occupies the memory it needs ● Read, Write, Add, Remove is O(1) ● No Index, searching is O(N) ● Use if you need to access all items ● Avoid using if you need to search by index or key LinkedList<T>
  • 22. ● TValue is sorted automatically by TKey ● Read, Write are O(logN) ● Add, Remove are O(N) ● Less Memory Footprint than Alternative ● Slower than Alternative SortedList<TKey, TValue>
  • 23. ● TValue is sorted automatically by TKey ● Self Balancing Binary Search Tree ● Read, Write, Add, Remove are O(logN)* ● Use if you need all items sorted ● Use if you want to search using Key SortedDictionary<TKey, TValue>
  • 24. Balanced vs Unbalanced Binary Search Tree SortedDictionary<TKey, TValue>
  • 25. ● Read Only Wrapper ● Receives List<T> as parameter ● Source list cannot be modified through wrapper ● Source list can be modified directly ● Modifications are reflected ● Not Thread-safe, Liability ● Use it when you want to prevent modification under certain contexts. ReadOnlyCollection<T>
  • 26. ● Has events for when elements in collection change: ○CollectionChanged ● Think of the event as a Triggers (SQL) ● Use if you need to trigger events when elements are added/removed or properties changed ObservableCollection<T>
  • 27. ● Cannot be Modified ● Thread-Safe ● Use if you want to access list in multiple threads, but not write or change ImmutableList<T>
  • 28. ● Primitive Type ● Succeded by List<T> ● Technically not Generic but Allowed ● Marginally better performance ● Can’t change size ● Use it if you really need maximum bare-metal hardware performance //Example of Array with 10 users User[] users = new User[10]; //Example of TWO DIMENSIONAL Array with 10x10 users User[][] users = new User[10][]; for (int i=0;i<10;i++) users[i] = new User[10]; What about System.Array?
  • 29. ● If you don’t know, then just use List<T> ● Only use LinkedList<T> if: ○need low memory footprint ○no need for index or key ○loop over all items ● As Hardware becomes more powerful, List<T> becomes the better option List<T> vs LinkedList<T>
  • 30. ● Use ImmutableList<T> if: ○Multithreading ● ReadOnlyCollection<T> is a wrapper, so it has low memory footprint ● ImmutableList<T> is a copy, so it has a high memory footprint ReadOnlyCollection<T> vs ImmutableList<T>
  • 31. ● Performance benefits only apply if using Index (Array, List) or Key (Dictionary) ● Searching using LINQ on a Collection defeats purpose of index/key ● LINQ search performance is O(N) About Searching and LINQ
  • 32. ● Using LINQ over Sort has no performance impact ● Sorting any type of Collections has a cost of O(NlogN) (QuickSort, InsertSort, MergeSort...) About Sorting
  • 33. ● Default Collection types not Thread-Safe (you can only use them in one thread) ● Thread-Safe version of Collections are: ○ConcurrentQueue (Queue) ○ConcurrentStack (Stack) ○ConcurrentDictionary (Dictionary) ○ConcurrentBag ○*System.Collections.Concurrent Collections and Multithreading
  • 34. ● Immutables can also be used, but they are read only ● Other Immutable Collections: ○ImmutableQueue (Queue) ○ImmutableStack (Stack) ○ImmutableList (List) ○ImmutableDictionary (Dictionary) ○*System.Collections.Immutable Collections and Multithreading
  • 35. ● Finally, Worst Case, if you need to, you can just use lock Collections and Multithreading void method(List<User> users) { lock(users) { //Do your multi threading stuff here users.Add(new User { … }); } }
  • 36. ● Remote communications and data transmission performance: O(N) ● Make sure the Database does all the hard work (filtering, sorting, joining) ● Think of Scalability About Collections and Databases
  • 37. ● When exposing collections in WebAPI’s, Microsoft recommends returning interfaces rather than implementations. ○IEnumerable ○ICollection ○IList, IDictionary… ● Return Empty Collection ● Don’t return NULL About Collections and Web API
  • 38. ● O(1): Most simple operations ● O(logN): Binary Searching ● O(N): Linear Searching, LINQ ● O(NlogN): Sorting ● O(N2): Nested loops (Ex: for in a for) Common Big-O Calculations
  • 39. You are now a Collection expert!... sort of... Questions? ...Aaaaaaaand… THAT’S IT!