presentation dot(net)

Upload: sourabh-tejawat

Post on 08-Apr-2018

231 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/7/2019 Presentation Dot(Net)

    1/85

    Elements of .NETElements of .NET

    Mahesh PrakriyaMahesh Prakriya

    Program ManagersProgram Managers

    Microsoft CorporationMicrosoft Corporation

  • 8/7/2019 Presentation Dot(Net)

    2/85

    OutlineOutline

    Blueprint and GoalsBlueprint and Goals Execution TimeExecution Time

    PerformancePerformance

    Design and Compile TimeDesign and Compile Time

    Deployment TimeDeployment Time

    SummarySummary

  • 8/7/2019 Presentation Dot(Net)

    3/85

    Open Internet ProtocolsOpen Internet Protocols

    SOAP, SCL, DISCO, HTTPSOAP, SCL, DISCO, HTTP

    SMTP, XML, WAP, XSDSMTP, XML, WAP, XSD

    The .NET Big PictureThe .NET Big Picture

    Your ApplicationYour Application

    and Web Serviceand Web Service

    Your ApplicationYour Applicationand Web Serviceand Web Service

    .NET.NETFrameworFramewor

    kk

    .NET.NETFrameworFramewor

    kk

    WindowsWindowsCE, ME,CE, ME,

    2000, .NET2000, .NET

    WindowsWindowsCE, ME,CE, ME,

    2000, .NET2000, .NET

    Opera

    ti

    on

    Operati

    on

    ss

    Opera

    tion

    Opera

    ti

    on

    ss

    End-UserEnd-UserClientsClients

    End-UserEnd-UserClientsClients

    OtherOtherApplicationsApplicationsUsing YourUsing Your

    ServiceService

    OtherOtherApplicationsApplicationsUsing YourUsing Your

    ServiceService

    OrchestratioOrchestrationn

    OrchestratioOrchestrationn

    Your Internal ServicesYour Internal Services

    Your Internal ServicesYour Internal Services

    .NET Enterprise.NET Enterprise

    ServersServers

    .NET Enterprise.NET Enterprise

    ServersServers

    Building BlockBuilding BlockServicesServices

    Building BlockBuilding BlockServicesServices

    Public Web ServicesPublic Web Services

    Public Web ServicesPublic Web Services

    VisualVisualStudio.NEStudio.NE

    TT

    VisualVisualStudio.NEStudio.NE

    TT

  • 8/7/2019 Presentation Dot(Net)

    4/85

    .NET Frameworks and the.NET Frameworks and the

    Common Language RuntimeCommon Language Runtime

    .NET.NET

    FrameworFrameworkk

    .NET.NET

    FrameworFrameworkk

    WindowsWindowsCE, ME,CE, ME,

    2000, .NET2000, .NET

    WindowsWindowsCE, ME,CE, ME,

    2000, .NET2000, .NET

    Opera

    tio

    n

    Opera

    tio

    n

    ss

    Opera

    tio

    n

    Opera

    tio

    n

    ss

    OrchestratioOrchestrationn

    OrchestratioOrchestrationn

    Base ClassesBase Classes

    Base ClassesBase Classes

    Data & XMLData & XML

    Data & XMLData & XML

    UserUserInterfaceInterfaceWeb/WinWeb/Win

    FormsForms

    UserUserInterfaceInterfaceWeb/WinWeb/Win

    FormsForms

    Common LanguageCommon LanguageRuntimeRuntime

    Common LanguageCommon LanguageRuntimeRuntime

    Web ServicesWeb ServicesASP+ASP+

    Web ServicesWeb ServicesASP+ASP+

  • 8/7/2019 Presentation Dot(Net)

    5/85

    Design Goals of the CLRDesign Goals of the CLR

    Simplify DevelopmentSimplify Development

    Simplify DeploymentSimplify Deployment Side by Side ExecutionSide by Side Execution Rich, Multi Language SupportRich, Multi Language Support

    SecuritySecurity Performance, Scalability &Performance, Scalability &

    ReliabilityReliability

  • 8/7/2019 Presentation Dot(Net)

    6/85

    Simpler DevelopmentSimpler Development

    Write less, Reuse moreWrite less, Reuse more

    Broadly available Frameworks classesBroadly available Frameworks classes Implementation inheritance for more reuseImplementation inheritance for more reuse

    Language independent reuseLanguage independent reuse

    Eliminate Plumbing CodeEliminate Plumbing Code No IUnknown, Class Factories, etcNo IUnknown, Class Factories, etc

    No GUIDS, HRESULTS, Type Libraries, etcNo GUIDS, HRESULTS, Type Libraries, etc

  • 8/7/2019 Presentation Dot(Net)

    7/85

    More reliable code

    No Reference counting

    Dynamic Binding

    Type safety

    Great tools support

    VS, Compilers, Debuggers, Profilers

    Simpler Development (contd..)

  • 8/7/2019 Presentation Dot(Net)

    8/85

    Simpler DeploymentSimpler Deployment

    No registration, zero impact installNo registration, zero impact install XCOPY deployment, incrementalXCOPY deployment, incremental

    downloaddownload

    Application isolationApplication isolation Applications unaffected by other appsApplications unaffected by other apps

    Sharing must be done explicitlySharing must be done explicitly

    Side-by-side versions ofSide-by-side versions of

    componentscomponents Use multiple versions simultaneouslyUse multiple versions simultaneously

    Per application administrative policyPer application administrative policy

  • 8/7/2019 Presentation Dot(Net)

    9/85

    Multiple LanguagesMultiple Languages

    (Common Type System)(Common Type System)

    Provides built-in data typesProvides built-in data types

    Provides mechanism to define,Provides mechanism to define,manage and use new typesmanage and use new types

    Provide common type representationProvide common type representationacross all languagesacross all languages

    Cross language inheritance,Cross language inheritance,exceptions, etcexceptions, etc

  • 8/7/2019 Presentation Dot(Net)

    10/85

    CLS: Designing For ReachCLS: Designing For Reach

    COBOLCOBOL C++C++

    CommonCommonType SystemType System

    CLS

    MicrosoftMicrosoft

    ManagedManagedC++C++

    ExtensionsExtensions

    FujitsuFujitsu

    COBOLCOBOL

    ExtensionsExtensions

    Common Type System is too big for any single languageCommon Type System is too big for any single language

    Common Language Specification is for cross-language useCommon Language Specification is for cross-language use

  • 8/7/2019 Presentation Dot(Net)

    11/85

    15+ languages already supporting the CLR

    VB, C++, C#, JScript, Cobol, Fortran, Pascal,Smalltalk, Perl, Python, more to come

    Great tools support

    Built in not bolted onVS IP program

    Multiple Languages (Examples)

  • 8/7/2019 Presentation Dot(Net)

    12/85

    Evidence Based SecurityEvidence Based Security

    Code IdentityCode Identity In addition to user identityIn addition to user identity Based on Code origin, Publisher, etcBased on Code origin, Publisher, etc

    Protected access to resourcesProtected access to resources Access protected with permission checksAccess protected with permission checks

    Access based on evidenceAccess based on evidence Including code identity, user identity,Including code identity, user identity,

    moremore

    Checks can be declarative or imperativeChecks can be declarative or imperative Declared on class or methodDeclared on class or method Embedded within codeEmbedded within code

  • 8/7/2019 Presentation Dot(Net)

    13/85

    Performance, Scalability &Performance, Scalability &ReliabilityReliability Improved PerformanceImproved Performance

    ASP.NET 2-3x that of ASP & JSPASP.NET 2-3x that of ASP & JSP Scalable from small device to Web farmScalable from small device to Web farm

    Same development toolsSame development tools

    Automatic memory managementAutomatic memory management

    Self-configuringSelf-configuring Dynamically tuningDynamically tuning

    Asynchronous messagingAsynchronous messaging Object remotingObject remoting

    EventsEvents

  • 8/7/2019 Presentation Dot(Net)

    14/85

    OutlineOutline

    Blueprint and GoalsBlueprint and Goals Execution TimeExecution Time

    PerformancePerformance

    Design and Compile TimeDesign and Compile Time

    Deployment TimeDeployment Time

    SummarySummary

  • 8/7/2019 Presentation Dot(Net)

    15/85

    Execution ModelExecution Model

    VBVB VCVC C#C#

    ILILNativeNative

    CodeCode

    Econo-JITEcono-JITCompilerCompiler

    Standard JITStandard JITCompilerCompiler

    NativeNative

    CodeCode

    Install timeInstall time

    Code GenCode Gen

    Common Language RuntimeCommon Language Runtime All codecompiled.

    No

    Interpreter

    Not in V1Not in V1

  • 8/7/2019 Presentation Dot(Net)

    16/85

    Managed CodeManaged Code

    Managed code provides...Managed code provides... Metadata describing dataMetadata describing data

    Location of references to objectsLocation of references to objects

    Exception handling tablesException handling tables

    So runtime can provideSo runtime can provide

    Debugging and profilingDebugging and profiling InteroperabilityInteroperability

    Exception handlingException handling

    SecuritySecurity

    Automatic lifetime managementAutomatic lifetime management

  • 8/7/2019 Presentation Dot(Net)

    17/85

    Runtime Execution ModelRuntime Execution Model

    ClassClassLoaderLoader

    IL to nativeIL to native

    code compilercode compiler

    CPUCPUSecuritySecurity

    SystemSystem

    ManagedManaged

    NativeNative

    CodeCode

    AssemblyAssembly

    First callFirst call

    to methodto method

    First referenceFirst reference

    toto typetype

    ExecutionExecution

    SupportSupport

    AssemblyAssembly

    ResolverResolver

    First referenceFirst reference

    to Assemblyto Assembly

  • 8/7/2019 Presentation Dot(Net)

    18/85

    IL: Key Design PointsIL: Key Design Points

    Supports any languageSupports any language Stack-based makes it easy forStack-based makes it easy for

    compiler writerscompiler writers

    Compilation, not interpretationCompilation, not interpretation Operations are typeless (e.g., add)Operations are typeless (e.g., add) Value types (C structs)Value types (C structs)

    Size-agnostic (32/64 bit) integersSize-agnostic (32/64 bit) integers Pointers with arithmetic andPointers with arithmetic and

    indirectionindirection

    Verification conditions specifiedVerification conditions specified

  • 8/7/2019 Presentation Dot(Net)

    19/85

    InnovationsInnovations

    Typesafety isnt requiredTypesafety isnt required Full C++ support, including pointersFull C++ support, including pointers

    Value typesValue types C structs that interconvert with objectsC structs that interconvert with objects User-defined types just like built-insUser-defined types just like built-ins

    Size-agnostic (32/64 bit) integersSize-agnostic (32/64 bit) integers Managed (interior) pointers, pinningManaged (interior) pointers, pinning Typed references (dynamically typedTyped references (dynamically typed

    pointers)pointers)

    Strongly typed variable argument listsStrongly typed variable argument lists

  • 8/7/2019 Presentation Dot(Net)

    20/85

    Compiling IL To NativeCompiling IL To Native

    JIT CompilerJIT Compiler

    Generates optimized native code from ILGenerates optimized native code from IL Includes verification of IL codeIncludes verification of IL code

    Install time code generationInstall time code generation

    Done at install timeDone at install time Reduces start-up timeReduces start-up time

    Native code has version checks and revertsNative code has version checks and revertsto runtime JIT if they failto runtime JIT if they fail

  • 8/7/2019 Presentation Dot(Net)

    21/85

  • 8/7/2019 Presentation Dot(Net)

    22/85

    Pre-JIT Code GenerationPre-JIT Code Generation

    A Pre-JITed Assembly is a persisted form ofA Pre-JITed Assembly is a persisted form ofJITed MSILJITed MSIL

    Reduces app startup time by eliminating JITReduces app startup time by eliminating JITcompilation from app run timecompilation from app run time

    Done at install timeDone at install time Can be run manuallyCan be run manually V.Next will have an automatic serviceV.Next will have an automatic service

    Pre-JITed code has version checks and reverts toPre-JITed code has version checks and reverts toruntime JIT if they failruntime JIT if they fail

    Could perform more optimizations than JIT,Could perform more optimizations than JIT,doesnt in V1 due to scheduledoesnt in V1 due to schedule

    Contains more indirections/runtime fix-ups thanContains more indirections/runtime fix-ups thanJITed codeJITed code

  • 8/7/2019 Presentation Dot(Net)

    23/85

    Pre-JIT Pre LoadingPre-JIT Pre Loading

    A Pre-JITed Assembly also contains persistedA Pre-JITed Assembly also contains persistedform of the class layoutform of the class layout

    Saves time at runtime to compute the classSaves time at runtime to compute the classlayout/v-tableslayout/v-tables

    Runtime Loader simply maps in the pre-computedRuntime Loader simply maps in the pre-computedclass layout in the assemblyclass layout in the assembly

    Load order optimization (LDO)Load order optimization (LDO) Profile/Scenario driven optimizationsProfile/Scenario driven optimizations

    Order the class layout info based on load orderOrder the class layout info based on load order

    Order methods based on locality of executionOrder methods based on locality of execution

    Improves working set by touching fewer pagesImproves working set by touching fewer pages

  • 8/7/2019 Presentation Dot(Net)

    24/85

    GC - OverviewGC - Overview

    State of the art Mark and CompactState of the art Mark and CompactGarbage CollectorGarbage Collector

    Maintains multiple GenerationsMaintains multiple Generations

    Based on Object Lifetime (G0->G1->G2)Based on Object Lifetime (G0->G1->G2)

    Keeps locality of reference intactKeeps locality of reference intact

    Low fragmentation, low memoryLow fragmentation, low memory

    overheadoverhead

  • 8/7/2019 Presentation Dot(Net)

    25/85

    GC Overview (contd..)GC Overview (contd..)

    Cache consciousCache conscious

    Gen0 fits in L2 cacheGen0 fits in L2 cache Two GCs architectures providedTwo GCs architectures provided

    Server multi-thread, highly-scaleableServer multi-thread, highly-scaleableGCGC

    Client single-threaded, concurrent GCClient single-threaded, concurrent GC

  • 8/7/2019 Presentation Dot(Net)

    26/85

    GC - PerfGC - Perf

    Perf of GC allocation similar to HeapPerf of GC allocation similar to Heap

    allocationallocation Limited by PC Bus speedLimited by PC Bus speed

    Typical Pause time (on a P200):Typical Pause time (on a P200):

    < 1ms for Gen 0< 1ms for Gen 0 < 10ms for Gen 1< 10ms for Gen 1

    Full GC varies with working setFull GC varies with working set

    InfrequentInfrequent

  • 8/7/2019 Presentation Dot(Net)

    27/85

    Exception HandlingException Handling

    Language neutral exception modelLanguage neutral exception model Supports both typed and filtered exceptionsSupports both typed and filtered exceptions

    Compilers emit EH tablesCompilers emit EH tables Handlers located based on EH TablesHandlers located based on EH Tables

    2 pass algorithm,2 pass algorithm,

    Find handler, handle exceptionFind handler, handle exception Very little overhead in the non-exceptionalVery little overhead in the non-exceptional

    casecase Tightly integrated with Structured ExceptionTightly integrated with Structured Exception

    HandlingHandling

  • 8/7/2019 Presentation Dot(Net)

    28/85

    Managed DataManaged Data

    Lifetime Managed by Runtime (GC)Lifetime Managed by Runtime (GC) Compacting GC eliminates fragmentation andCompacting GC eliminates fragmentation and

    reduces working setreduces working set Data may be moved during collectionData may be moved during collection

    Object references are updated automaticallyObject references are updated automatically

    No more intrusive than a page faultNo more intrusive than a page fault

    Layout Provided by RuntimeLayout Provided by Runtime Usually automaticUsually automatic

    Metadata can specifyMetadata can specify

    Order, Packing, Explicit layoutOrder, Packing, Explicit layout

  • 8/7/2019 Presentation Dot(Net)

    29/85

    Calling Unmanaged CodeCalling Unmanaged Code

    CommonCommon

    LanguageLanguage

    RuntimeRuntime

    UnmanagedUnmanagedCodeCode

    ManagedManaged

    ObjectObject

    UnmanagedUnmanaged

    ObjectObject

    ManagedManaged

    ObjectObject

    Unmanaged CodeUnmanaged Code

  • 8/7/2019 Presentation Dot(Net)

    30/85

    COM InteropCOM Interop

    Provides a bridge between the runtime andProvides a bridge between the runtime andCOMCOM and vice versaand vice versa

    Maintains programming model consistencyMaintains programming model consistencyon both sideson both sides

    Abstracts the inconsistencies between theAbstracts the inconsistencies between thetwo modelstwo models Different data typesDifferent data types Method signaturesMethod signatures Exception/HresultsException/Hresults Activation modelsActivation models

  • 8/7/2019 Presentation Dot(Net)

    31/85

    Platform Invoke (P/Invoke)Platform Invoke (P/Invoke)

    Provides access to static entryProvides access to static entry

    points in unmanaged DLLspoints in unmanaged DLLs Similar to:Similar to:

    VB Declare statementVB Declare statement Load library / GetProcAddressLoad library / GetProcAddress

    Requires method definition withRequires method definition withcustom attributecustom attribute

    Uses same underlying marshalingUses same underlying marshaling

    service as COM Interopservice as COM Interop

  • 8/7/2019 Presentation Dot(Net)

    32/85

    Runtime makes it simple to call the OSRuntime makes it simple to call the OS

    At a transition, the RuntimeAt a transition, the Runtime Switches thread mode so that GC wontSwitches thread mode so that GC wont

    block on threads in unmanaged codeblock on threads in unmanaged code Erects an EH frame on calls in to managedErects an EH frame on calls in to managed

    code for EH clean upcode for EH clean up

    Performs requested data type marshalingPerforms requested data type marshaling Fixes calling conventionFixes calling convention Protects callee saved registersProtects callee saved registers

    Optionally takes control of threadOptionally takes control of thread

    Transitions (mgd/unmgd)Transitions (mgd/unmgd)

  • 8/7/2019 Presentation Dot(Net)

    33/85

    Transition costTransition cost

    Baseline costBaseline cost PInvokePInvoke

    As low as 8 instructions if no marshalingAs low as 8 instructions if no marshalingrequiredrequired

    31 if marshaling is required31 if marshaling is required COM InteropCOM Interop

    About 65 instructionsAbout 65 instructions Incremental parameter marshaling costIncremental parameter marshaling cost

    Primitives are almost freePrimitives are almost free Classes with explicit layout are almost freeClasses with explicit layout are almost free

    Data transformation (e.g. Unicode -> Ansi, Object-Data transformation (e.g. Unicode -> Ansi, Object->

  • 8/7/2019 Presentation Dot(Net)

    34/85

    OutlineOutline

    Blueprint and GoalsBlueprint and Goals Execution TimeExecution Time

    PerformancePerformance

    Design and Compile TimeDesign and Compile Time

    Deployment TimeDeployment Time

    SummarySummary

  • 8/7/2019 Presentation Dot(Net)

    35/85

    Performance -Performance -OutlineOutline Preliminary, Beta1 Perf DataPreliminary, Beta1 Perf Data

    Web AppsWeb Apps

    Client AppsClient Apps

    BenchmarksBenchmarks

    Tips & TricksTips & Tricks Useful Perf ToolsUseful Perf Tools

    CLR, ASP+ Perf CountersCLR, ASP+ Perf Counters

    ProfilersProfilers

  • 8/7/2019 Presentation Dot(Net)

    36/85

    Performance Web AppsPerformance Web Apps

    Porting existing benchmarks and samplesPorting existing benchmarks and samples

    NT site on ms.com, Nile, Duwamish, FMStocksNT site on ms.com, Nile, Duwamish, FMStocksetc.etc.

    Porting and Measuring Real CustomerPorting and Measuring Real CustomerAppsApps

    US West DSL ordering app, etc.US West DSL ordering app, etc. Measuring published benchmarks such asMeasuring published benchmarks such as

    Doculabs NileDoculabs Nile

    Benchmarking ourselves againstBenchmarking ourselves against

    competitive technologies such as JSPcompetitive technologies such as JSP

  • 8/7/2019 Presentation Dot(Net)

    37/85

    Web Apps - NT Home PageWeb Apps - NT Home Page

    ~ 3KLOC of ASP~ 3KLOC of ASP Historically used by NT & IIS PerfHistorically used by NT & IIS Perf

    Teams for benchmarkingTeams for benchmarking

    Implemented in all VS languages andImplemented in all VS languages andJSPJSP

  • 8/7/2019 Presentation Dot(Net)

    38/85

    Web Apps - NT Home PageWeb Apps - NT Home Page(contd..)(contd..) Gradations exist from unmanaged (ASP) toGradations exist from unmanaged (ASP) to

    fully managed codefully managed code

    ASP implementation talks to a COM object forASP implementation talks to a COM object fordictionary look upsdictionary look ups

    ASP+ Interop implementation is the portedASP+ Interop implementation is the portedASP page; interops with the same COMASP page; interops with the same COMObjectObject

    ASP+ fully managed implementation usesASP+ fully managed implementation uses

    a .NET collection classa .NET collection class

    N T H o m e P a g e P e r f o n P II 4 5 0 X e o n 2 56 M B o n W 2 K 1 P r o2 P

  • 8/7/2019 Presentation Dot(Net)

    39/85

    g

    ( T a lle r is b e t te r )

    0

    5 0

    100150

    200

    250

    300350

    400

    450

    Al la i re - JS P(Apache ) W e bs p h er e3 .5 - JS P

    (Apache )

    VB S - AS P VB - AS P + C # - AS P + C # - W ebGarden

    Requests/Sec

    2 P r o4 P r o

  • 8/7/2019 Presentation Dot(Net)

    40/85

    N T H o m e P a g e P e r f - In t e r o p S c e n a r io s

    on P II 450 4 Proc Xe on 256M B - Bu i ld 2009 (Ta lle

    0

    5 0

    1 00

    1 50

    2 00

    2 50

    3 00

    3 50

    4 00

    Requests/Sec

    Throughput is 81% of

    fully managed code

  • 8/7/2019 Presentation Dot(Net)

    41/85

    Web Apps - NileWeb Apps - Nile

    Doculabs Nile is an e-commerce bookstoreDoculabs Nile is an e-commerce bookstoreapp like Amazonapp like Amazon

    Web front end to a large back-end DBWeb front end to a large back-end DB

    Historically used by Doculabs to evaluateHistorically used by Doculabs to evaluaterelative perf of app serversrelative perf of app servers

    About 4 KLOC total of HTML, ASP+, C#About 4 KLOC total of HTML, ASP+, C# The perf test measures the throughput withThe perf test measures the throughput with

    a load of 64 simultaneous usersa load of 64 simultaneous users

    N i l e a p p l i c a t i o n p e r fo r m a n c e o n 4 w a y 5 5 0 M h z

  • 8/7/2019 Presentation Dot(Net)

    42/85

    N i l e a p p l i c a t i o n p e r fo r m a n c e o n 4 w a y 5 5 0 M h z

    2 0 1 6 b u i l d ( t a l l e r i s b e t te r )

    5 0 0

    1 0 0 0

    1 5 0 0

    2 0 0 0

    2 5 0 0

    3 0 0 0

    3 5 0 0

    4 0 0 0

    R

    equestsperSecond

    A S P ( V

    A S P + (

    V C 6 / O

  • 8/7/2019 Presentation Dot(Net)

    43/85

    Working SetWorking Set

    C#C# Console.Writeline("HelloConsole.Writeline("Hello

    World")World") Beta1 working set is 4.x MBBeta1 working set is 4.x MB RTM goal is 2MBRTM goal is 2MB Issues: CLR BBT, Fusion, Pre-JIT, Issues: CLR BBT, Fusion, Pre-JIT,

    Empty Win FormEmpty Win Form Beta1 working set is 9.4MBBeta1 working set is 9.4MB RTM goal is 4MBRTM goal is 4MB

    Issues: Win Forms, CLR, GDI+Issues: Win Forms, CLR, GDI+

  • 8/7/2019 Presentation Dot(Net)

    44/85

    Win Forms ScenarioWin Forms Scenario

    Startup time today worse than VB6Startup time today worse than VB6 Mostly due to working set issues..Mostly due to working set issues..

    Currently Pri 1 Perf issue to work onCurrently Pri 1 Perf issue to work on

    for Beta2for Beta2

  • 8/7/2019 Presentation Dot(Net)

    45/85

    BenchmarksBenchmarks BYTEMark is a benchmark used by BYTEBYTEMark is a benchmark used by BYTE

    magazinemagazine

    Numerically Intensive used to evaluateNumerically Intensive used to evaluateprocessor performanceprocessor performance

    Relative Index; Normalized to 90 MHz DellRelative Index; Normalized to 90 MHz DellPentiumPentium

    BYTEMark, coversBYTEMark, covers Numeric sort, String sort, Bitfield, Fourier, FPNumeric sort, String sort, Bitfield, Fourier, FP

    Emulation, Assignment, IDEA, Huffman, NeuralEmulation, Assignment, IDEA, Huffman, NeuralNet and LU DecompositionNet and LU Decomposition

    Byte mark on dual PII 450 Xe on 2

  • 8/7/2019 Presentation Dot(Net)

    46/85

    yte a o dua 50 e o

    (Talle r is Be tter)

    7

    7.5

    8

    8.5

    9

    9.5

    10

    V C7Native

    /O2

    VC7-IL/O 2

    V C6 /02 C# - CLR2016

    Java - M SVM 3310

    Int-Index

  • 8/7/2019 Presentation Dot(Net)

    47/85

    Tips & TricksTips & Tricks

    Web GardensWeb Gardens

    Early BindingEarly Binding Pre-JIT AssembliesPre-JIT Assemblies

    Transitions (mgd/unmgd)Transitions (mgd/unmgd)

    Value TypesValue Types Strings and ArraysStrings and Arrays

    Inlining hintsInlining hints

    W b G d

  • 8/7/2019 Presentation Dot(Net)

    48/85

    Web GardensWeb Gardens

    Ability to run application in multipleAbility to run application in multipleworker processesworker processes Each process has processor affinityEach process has processor affinity

    Must be explicitly enabledMust be explicitly enabled Performance win in many SMPPerformance win in many SMP

    scenariosscenarios Eliminates cross processor lockEliminates cross processor lock

    contentioncontention

    Ideal for large SMP systemsIdeal for large SMP systems

  • 8/7/2019 Presentation Dot(Net)

    49/85

    Use Early BindingUse Early Binding

    VB and JScript support early and lateVB and JScript support early and latebindingbinding Late binding can negate compilationLate binding can negate compilation

    Late Binding requires work at runtimeLate Binding requires work at runtime Late Binding (slower)Late Binding (slower)

    Early Binding (better performance)Early Binding (better performance)

    Dim ds

    Ds = New DataSet

    Dim ds As New DataSet

  • 8/7/2019 Presentation Dot(Net)

    50/85

    T iti ( d/ d)T iti ( d/ d)

  • 8/7/2019 Presentation Dot(Net)

    51/85

    Transitions (mgd/unmgd)Transitions (mgd/unmgd)

    Managed to Unmanaged transitions happenManaged to Unmanaged transitions happenwhen you usewhen you use

    Platform Invoke, COM interop, or It Just WorksPlatform Invoke, COM interop, or It Just Works Runtime keeps track of exceptions,Runtime keeps track of exceptions,

    marshals parameters, etc.marshals parameters, etc. Cost is on the order of 10-50 instructionsCost is on the order of 10-50 instructions

    This cost should be considered whenThis cost should be considered whenmaking a call to unmanaged codemaking a call to unmanaged code Use a chunky versus chatty APIUse a chunky versus chatty API Amortize the cost of a transitionAmortize the cost of a transition

    Minimize transitionsMinimize transitions

    V l TV l T

  • 8/7/2019 Presentation Dot(Net)

    52/85

    Value TypesValue Types

    Think OO structs on the stackThink OO structs on the stack Passed by value (default) andPassed by value (default) and

    referencereference

    Use Value Types for small dataUse Value Types for small data .NET Frameworks primitive types are.NET Frameworks primitive types are

    value types (for perf)value types (for perf)

    Useful for items like Point (x,yUseful for items like Point (x,ycoordinates)coordinates)

  • 8/7/2019 Presentation Dot(Net)

    53/85

    Strings, Arrays, InliningStrings, Arrays, Inlining

    HintsHints

    Strings are immutableStrings are immutable

    Use the mutable StringBuilder object whenUse the mutable StringBuilder object whenbuilding strings in several stepsbuilding strings in several steps

    Do not cache String or Array lengthsDo not cache String or Array lengths

    for (i=0; i < A.Length; i++) {}for (i=0; i < A.Length; i++) {}

    For best inlining performanceFor best inlining performance Minimize the use of virtual methodsMinimize the use of virtual methods

    Use sealed typesUse sealed types

    P f C t O iP f C t O i

  • 8/7/2019 Presentation Dot(Net)

    54/85

    Perf Counters - OverviewPerf Counters - Overview

    Perf Counters are metrics aboutPerf Counters are metrics aboutresource usage exposed by the .NETresource usage exposed by the .NETFrameworkFramework

    First line of defenseFirst line of defense Always availableAlways available

    Can be obtained non-intrusively even inCan be obtained non-intrusively even in

    production environmentproduction environment

    R ti P f C t (I)R ti P f C t (I)

  • 8/7/2019 Presentation Dot(Net)

    55/85

    Runtime Perf Counters (I)Runtime Perf Counters (I)

    Loader:Loader: % of Execution Time Loading% of Execution Time Loading

    AppDomains, Assemblies, Classes etc.AppDomains, Assemblies, Classes etc. Memory:Memory:

    % Time in GC, bytes/sec, heap sizes and various% Time in GC, bytes/sec, heap sizes and variousmetrics related to GC GenXmetrics related to GC GenX

    Interop:Interop: managed to unmanaged transitionsmanaged to unmanaged transitions Metrics on marshalling, stubs etc.Metrics on marshalling, stubs etc.

    Contexts and Remoting:Contexts and Remoting: Remote Calls/Sec, Total Remote CallsRemote Calls/Sec, Total Remote Calls # of Channels, Contexts, Proxies etc.# of Channels, Contexts, Proxies etc.

    R ti P f C t (II)R ti P f C t (II)

  • 8/7/2019 Presentation Dot(Net)

    56/85

    Runtime Perf Counters (II)Runtime Perf Counters (II)

    Threads and Locks:Threads and Locks: # of logical and physical threads# of logical and physical threads

    Contention Rate/sec, Total # of contentionsContention Rate/sec, Total # of contentions

    JIT Compilation:JIT Compilation: % of time in JIT, # of methods JITed, MSIL% of time in JIT, # of methods JITed, MSIL

    Bytes JITed/sec, etc.Bytes JITed/sec, etc. Others include Exceptions, SecurityOthers include Exceptions, Security

    and Networkingand Networking

    All of the above are available throughAll of the above are available through

    System.Diagnostics.PerformanceCounterSystem.Diagnostics.PerformanceCounter

    ASP P f C tASP+ P f C t

  • 8/7/2019 Presentation Dot(Net)

    57/85

    ASP+ Perf CountersASP+ Perf Counters

    Requests/SecRequests/Sec Request BytesRequest Bytes inin TotalTotal

    Request BytesRequest Bytes outout TotalTotal

    Requests ExecutingRequests Executing

    Requests TotalRequests Total

    Application RestartsApplication Restarts

    P fil A hit tP fil A hit t

  • 8/7/2019 Presentation Dot(Net)

    58/85

    Profiler ArchitectureProfiler Architecture

    ExecutionExecution

    EngineEngine

    ProfilingProfiling

    APIAPIMonitoringMonitoring

    AgentAgent

    Collection/Collection/DisplayDisplay

    ConsoleConsole

    ProgramProgram

    under testunder test

  • 8/7/2019 Presentation Dot(Net)

    59/85

    O tliO tline

  • 8/7/2019 Presentation Dot(Net)

    60/85

    OutlineOutline

    Blueprint and GoalsBlueprint and Goals Execution TimeExecution Time

    PerformancePerformance

    Design and Compile TimeDesign and Compile Time Deployment TimeDeployment Time

    SummarySummary

    P d i M d C dProducing Managed Code

  • 8/7/2019 Presentation Dot(Net)

    61/85

    Producing Managed CodeProducing Managed Code

    Unmanaged compilers use the CLRUnmanaged compilers use the CLRmetadata APIs to emit managedmetadata APIs to emit managedmetadata to a binary filemetadata to a binary file IMetadataEmit, IMetadataImportIMetadataEmit, IMetadataImport

    Managed types exist for managedManaged types exist for managed

    Compilers to do the sameCompilers to do the same Reflection, Reflection.EmitReflection, Reflection.Emit

    Binary files use standard PE fileBinary files use standard PE fileformatformat

    M t d tMetadata

  • 8/7/2019 Presentation Dot(Net)

    62/85

    MetadataMetadata

    Language neutral type info and moreLanguage neutral type info and more Generated from source code (no IDL)Generated from source code (no IDL)

    Key to simpler programming modelKey to simpler programming model Common way to describe and use typesCommon way to describe and use types

    Generated automatically by compilersGenerated automatically by compilers

    Stored along with code in executable fileStored along with code in executable file binary formatbinary format

    Required for execution (not optional)Required for execution (not optional) Convertible to/from XML Schema & COM tlbConvertible to/from XML Schema & COM tlb

    Whats In The MetadataWhats In The Metadata

  • 8/7/2019 Presentation Dot(Net)

    63/85

    Whats In The MetadataWhats In The Metadata

    Description of deployment unitDescription of deployment unit(assembly)(assembly)

    Identity: name, version, culture[,Identity: name, version, culture[,public key]public key]

    What types are exportedWhat types are exported

    What types are referencedWhat types are referenced

    Security permissions needed to runSecurity permissions needed to run

    Whats In The MetadataWhats In The Metadata

  • 8/7/2019 Presentation Dot(Net)

    64/85

    Whats In The MetadataWhats In The Metadata(contd)(contd)

    Description of typesDescription of types

    Name, visibility, base class, interfacesName, visibility, base class, interfacesimplementedimplemented

    Members (methods, fields, properties,Members (methods, fields, properties,events, nested types)events, nested types)

    Custom attributesCustom attributes User-defined (author?)User-defined (author?)

    Compiler-defined (const)Compiler-defined (const)

    Framework-defined (DllImport, Obsolete)Framework-defined (DllImport, Obsolete)

  • 8/7/2019 Presentation Dot(Net)

    65/85

    Metadata: Creation AndMetadata: Creation And

    UseUse

    MetadataMetadata(and code)(and code)

    DebuggerDebugger

    SchemaSchema

    GeneratorGenerator

    ProfilerProfiler

    CompilersCompilers

    Proxy GeneratorProxy Generator

    Type BrowserType Browser

    CompilerCompiler

    SourceSourceCodeCode

    XML encodingXML encoding(SDL or SUDS)(SDL or SUDS)

    SerializationSerialization

    DesignersDesigners

    ReflectionReflection

    TLB ExporterTLB Exporter

    Other Tools Use MetadataOther Tools Use Metadata

  • 8/7/2019 Presentation Dot(Net)

    66/85

    Other Tools Use MetadataOther Tools Use Metadata

    Type viewers/Object browsersType viewers/Object browsers

    Documentation toolsDocumentation tools

    Reflections classesReflections classes

    Designers/WizardsDesigners/Wizards

    TLB importer and ExporterTLB importer and Exporter

    Debuggers/ProfilersDebuggers/Profilers

    OutlineOutline

  • 8/7/2019 Presentation Dot(Net)

    67/85

    OutlineOutline

    Blueprint and GoalsBlueprint and Goals Execution TimeExecution Time

    Design and Compile TimeDesign and Compile Time

    Deployment TimeDeployment Time PerformancePerformance

    SummarySummary

    Simplifying DeploymentSimplifying Deployment

  • 8/7/2019 Presentation Dot(Net)

    68/85

    Simplifying DeploymentSimplifying DeploymentWhats requiredWhats required

    Apps must be self describingApps must be self describing Enables zero-impact installEnables zero-impact install

    Version dependencies must beVersion dependencies must berecorded and enforcedrecorded and enforced

    Must remember last known goodMust remember last known good

    Support side by side componentsSupport side by side components Application isolationApplication isolation

    Both code and configuration dataBoth code and configuration data

    Enable partially trusted mobile codeEnable partially trusted mobile code

    AssembliesAssemblies

  • 8/7/2019 Presentation Dot(Net)

    69/85

    AssembliesAssembliesThe Building BlockThe Building Block

    Deployment unit for types andDeployment unit for types and

    resources: a logical dllresources: a logical dll

    Self describing through a manifestSelf describing through a manifest Fundamental unit of versioning, reuse,Fundamental unit of versioning, reuse,

    deployment and permission grants anddeployment and permission grants and

    requestsrequests Core to type loading and executionCore to type loading and execution

    Visibility boundaryVisibility boundary

    Type resolution scopeType resolution scope

    Versioning And SharingVersioning And Sharing

  • 8/7/2019 Presentation Dot(Net)

    70/85

    Versioning And SharingVersioning And Sharing

    Isolate components when possibleIsolate components when possible

    Sharing is not the defaultSharing is not the default Shared components are side by sideShared components are side by side

    Allows choice of versionAllows choice of version

    Publishers make compatibility statementsPublishers make compatibility statements

    Allow flexibility in versioning through policyAllow flexibility in versioning through policy Post deploymentPost deployment

    Applications do not impact others byApplications do not impact others by

    default!!default!!

  • 8/7/2019 Presentation Dot(Net)

    71/85

    Versioning And SharingVersioning And Sharing

  • 8/7/2019 Presentation Dot(Net)

    72/85

    Versioning And SharingVersioning And SharingShared AssembliesShared Assemblies

    Assembly that is shared among severalAssembly that is shared among severalapplications on the machineapplications on the machine

    More stringent naming requirements (StrongMore stringent naming requirements (StrongNames)Names) UniquenessUniqueness Protection of the nameProtection of the name

    Identity on referenceIdentity on reference Typically deployed to the globalTypically deployed to the global

    assembly cacheassembly cache May also be privatized to app directoryMay also be privatized to app directory

    Versions are checked, version olicies a lVersions are checked, version policies apply

    At Runtime: What VersionAt Runtime: What Version

  • 8/7/2019 Presentation Dot(Net)

    73/85

    At Runtime: What VersionAt Runtime: What Versiongets Loaded?gets Loaded?

    Manifest records the version of eachManifest records the version of each

    dependency at build timedependency at build time By default: Bind to version in manifestBy default: Bind to version in manifest

    Can be overridden by policyCan be overridden by policy

    Applies only on references toApplies only on references toshared assembliesshared assemblies

    Version PolicyVersion Policy

  • 8/7/2019 Presentation Dot(Net)

    74/85

    Version PolicyVersion Policy

    Policy specified using XML configurationPolicy specified using XML configurationfilesfiles Application-specific policyApplication-specific policy

    Publisher policyPublisher policy

    Administrator policyAdministrator policy

    Versioning: The BigVersioning: The Big

  • 8/7/2019 Presentation Dot(Net)

    75/85

    Versioning: The BigVersioning: The BigPicturePicture

    App DirectoryApp Directory

    Ex:

    foo,Ver=1.0.0.0,

    PK= 23 43

    1) Original1) Original

    AssemblyAssembly

    ReferenceReference

    Ex:

    foo,Ver=2.0.2.0,

    PK= 23 43

    3) Post-Policy3) Post-Policy

    ReferenceReference

    Global Assembly CacheGlobal Assembly Cache

    4) Find4) Find

    AssemblyAssembly

    AppApp

    PolicyPolicyPubPub

    PolicyPolicyAdminAdmin

    PolicyPolicy

    Safe-ModeSafe-Mode

    2) Apply2) Apply

    PolicyPolicy

  • 8/7/2019 Presentation Dot(Net)

    76/85

    SummarySummary

  • 8/7/2019 Presentation Dot(Net)

    77/85

    SummarySummary

    Simpler Development, deployment,Simpler Development, deployment,administrationadministration

    Performant, Multi-language, secure &Performant, Multi-language, secure &scalablescalable

    Side by side versioningSide by side versioning

    Full interoperation with unmanaged codeFull interoperation with unmanaged code COM, Win32, your DLLsCOM, Win32, your DLLs

    Integrated & Comprehensive toolsIntegrated & Comprehensive toolssupportsupport

    You get a strong foundation for the future!You get a strong foundation for the future!

    Q ti ?Questions?

  • 8/7/2019 Presentation Dot(Net)

    78/85

    Questions?Questions?

    FinalizationFinalization

  • 8/7/2019 Presentation Dot(Net)

    79/85

    FinalizationFinalization

    Finalizers are not destructorsFinalizers are not destructors

    If youre holding onto an expensiveIf youre holding onto an expensiveresource dont wait for finalizationresource dont wait for finalization

    Instead, be sure to:Instead, be sure to:

    Implement close method on the objectImplement close method on the objectthat cleans up your resourcesthat cleans up your resources

    Suppress FinalizationSuppress Finalization

    Release the reference as soon as youreRelease the reference as soon as youre

    done by setting it to nulldone by setting it to null

    Finalization - SampleFinalization - Sample

  • 8/7/2019 Presentation Dot(Net)

    80/85

    Finalization - SampleFinalization - Sample

    f = new foo();f = new foo();

    .. // do some work.. // do some work

    // f is// f is a large, no-longer used object and thea large, no-longer used object and thereference is one that will stay in scope for somereference is one that will stay in scope for sometime to cometime to come

    f.close();f.close();

    f = null;f = null;

    void close() {void close() {//clean up resources could just call the//clean up resources could just call the

    finalizerfinalizer

    GC.SuppressFinalize(this);GC.SuppressFinalize(this);

    }}

    AssembliesAssemblies

  • 8/7/2019 Presentation Dot(Net)

    81/85

    AssembliesAssemblies

    Collections of types and bindingCollections of types and bindinginformationinformation

    Unit of deploymentUnit of deployment One or more files, independent ofOne or more files, independent of

    packagingpackaging Self-describing via metadata (manifest)Self-describing via metadata (manifest)

    Unit of VersioningUnit of Versioning Captured by compilerCaptured by compiler Policy per-application as well as per-Policy per-application as well as per-

    machinemachine

    Assemblies (contd )Assemblies (contd )

  • 8/7/2019 Presentation Dot(Net)

    82/85

    Assemblies (cont d..)Assemblies (cont d..)

    Security boundarySecurity boundary Assemblies are granted permissionsAssemblies are granted permissions

    Methods can demand proof that aMethods can demand proof that a

    permissionpermissionhas been granted to entire call chainhas been granted to entire call chain

    Mediate type import and exportMediate type import and export

    Types always referenced relative toTypes always referenced relative toassemblyassembly

    Assembly IdentityAssembly Identity

  • 8/7/2019 Presentation Dot(Net)

    83/85

    Assembly IdentityAssembly Identity

    Assemblies can be Private or SharedAssemblies can be Private or Shared Private used only by a single applicationPrivate used only by a single application

    Shared used by any installed applicationShared used by any installed application

    Shared assemblies are identified byShared assemblies are identified by Name such as System.DrawingName such as System.Drawing

    Publisher such as MicrosoftPublisher such as Microsoft Identified with publishers keyIdentified with publishers key

    Version 4 part version numberVersion 4 part version number

    Not associated with product versionNot associated with product version

    Culture - Easier localizationCulture - Easier localization

    Assembly StorageAssembly Storage

  • 8/7/2019 Presentation Dot(Net)

    84/85

    Assembly StorageAssembly Storage

    Private AssembliesPrivate Assemblies Installed in application directoryInstalled in application directory

    Xcopy deployment, Not registrationXcopy deployment, Not registration

    Zero impact install, copy and runZero impact install, copy and run

    Shared AssembliesShared Assemblies

    Installed in Global Assembly Cache (GAC)Installed in Global Assembly Cache (GAC) Extensive binding policy supportExtensive binding policy support

    Use latestUse latest

    Use specificUse specific

    SafemodeSafemode

    Assembly BindingAssembly Binding

  • 8/7/2019 Presentation Dot(Net)

    85/85

    Assembly BindingAssembly Binding

    Applications are configurable unitsApplications are configurable units Made up of one or more assembliesMade up of one or more assemblies

    Application-specific files or dataApplication-specific files or data

    Assemblies are located based onAssemblies are located based on Assembly Identity andAssembly Identity and

    The binding policy of the applicationThe binding policy of the application Applications can have private versionsApplications can have private versions

    of assembliesof assemblies