SlideShare a Scribd company logo
1 of 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

More Related Content

What's hot

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++)Sangharsh agarwal
 
Stl Containers
Stl ContainersStl Containers
Stl Containersppd1961
 
Stl (standard template library)
Stl (standard template library)Stl (standard template library)
Stl (standard template library)Hemant Jain
 
Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template LibraryKumar Gaurav
 
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 ArrayJeongbae Oh
 
Prototypes in Pharo
Prototypes in PharoPrototypes in Pharo
Prototypes in PharoESUG
 
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...GeeksLab Odessa
 
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...gjcross
 
Few simple-type-tricks in scala
Few simple-type-tricks in scalaFew simple-type-tricks in scala
Few simple-type-tricks in scalaRuslan Shevchenko
 
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 LibraryJoyjit Choudhury
 
Session 17 - Collections - Lists, Sets
Session 17 - Collections - Lists, SetsSession 17 - Collections - Lists, Sets
Session 17 - Collections - Lists, SetsPawanMM
 
Session 14 - Object Class
Session 14 - Object ClassSession 14 - Object Class
Session 14 - Object ClassPawanMM
 
Session 15 - Collections - Array List
Session 15 - Collections - Array ListSession 15 - Collections - Array List
Session 15 - Collections - Array ListPawanMM
 
Introductory Clojure Presentation
Introductory Clojure PresentationIntroductory Clojure Presentation
Introductory Clojure PresentationJay Victoria
 

What's hot (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
 

Similar to Collections and generics

CSharp for Unity - Day 1
CSharp for Unity - Day 1CSharp for Unity - Day 1
CSharp for Unity - Day 1Duong Thanh
 
Ledingkart Meetup #2: Scaling Search @Lendingkart
Ledingkart Meetup #2: Scaling Search @LendingkartLedingkart Meetup #2: Scaling Search @Lendingkart
Ledingkart Meetup #2: Scaling Search @LendingkartMukesh Singh
 
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...Magnus Sedlacek
 
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 KibanaMushfekur Rahman
 
Talk on Standard Template Library
Talk on Standard Template LibraryTalk on Standard Template Library
Talk on Standard Template LibraryAnirudh Raja
 
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 OpportunitiesDatabricks
 
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_iiiNico Ludwig
 
Programming for Performance
Programming for PerformanceProgramming for Performance
Programming for PerformanceCris Holdorph
 
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 ReaderAlluxio, Inc.
 
Mongo nyc nyt + mongodb
Mongo nyc nyt + mongodbMongo nyc nyt + mongodb
Mongo nyc nyt + mongodbDeep Kapadia
 
L1 - Recap.pdf
L1 - Recap.pdfL1 - Recap.pdf
L1 - Recap.pdfIfat Nix
 
Elasticsearch Architechture
Elasticsearch ArchitechtureElasticsearch Architechture
Elasticsearch ArchitechtureAnurag Sharma
 
Algorithms__Data_Structures_-_iCSC_2018.pptx
Algorithms__Data_Structures_-_iCSC_2018.pptxAlgorithms__Data_Structures_-_iCSC_2018.pptx
Algorithms__Data_Structures_-_iCSC_2018.pptxNurBudiNugroho
 
Advanced Non-Relational Schemas For Big Data
Advanced Non-Relational Schemas For Big DataAdvanced Non-Relational Schemas For Big Data
Advanced Non-Relational Schemas For Big DataVictor Smirnov
 

Similar to 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
 
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
 
Advanced Non-Relational Schemas For Big Data
Advanced Non-Relational Schemas For Big DataAdvanced Non-Relational Schemas For Big Data
Advanced Non-Relational Schemas For Big Data
 

More from Miguel Angel Teheran Garcia

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 FunctionsMiguel Angel Teheran Garcia
 
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...Miguel Angel Teheran Garcia
 
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.pptxMiguel Angel Teheran Garcia
 
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 conocerMiguel Angel Teheran Garcia
 
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 PlataformaMiguel Angel Teheran Garcia
 
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 MudBlazorMiguel Angel Teheran Garcia
 

More from 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
 

Recently uploaded

A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingShane Coughlan
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shardsChristopher Curtin
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptxVinzoCenzo
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITmanoharjgpsolutions
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecturerahul_net
 
SoftTeco - Software Development Company Profile
SoftTeco - Software Development Company ProfileSoftTeco - Software Development Company Profile
SoftTeco - Software Development Company Profileakrivarotava
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxRTS corp
 
VictoriaMetrics Anomaly Detection Updates: Q1 2024
VictoriaMetrics Anomaly Detection Updates: Q1 2024VictoriaMetrics Anomaly Detection Updates: Q1 2024
VictoriaMetrics Anomaly Detection Updates: Q1 2024VictoriaMetrics
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsJean Silva
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfkalichargn70th171
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxRTS corp
 

Recently uploaded (20)

A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptx
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh IT
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecture
 
SoftTeco - Software Development Company Profile
SoftTeco - Software Development Company ProfileSoftTeco - Software Development Company Profile
SoftTeco - Software Development Company Profile
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
 
VictoriaMetrics Anomaly Detection Updates: Q1 2024
VictoriaMetrics Anomaly Detection Updates: Q1 2024VictoriaMetrics Anomaly Detection Updates: Q1 2024
VictoriaMetrics Anomaly Detection Updates: Q1 2024
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero results
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
 

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!