SlideShare une entreprise Scribd logo
1  sur  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

Contenu connexe

Tendances

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
 

Tendances (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
 

Similaire à 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
 

Similaire à 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
 

Plus de 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
 

Plus 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
 

Dernier

The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 

Dernier (20)

The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 

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!