Beruflich Dokumente
Kultur Dokumente
FASTER
ASP.NET
1
JEFFREY RICHTER
JOHN ROBBINS
DAVID CONLIN
SHMUEL ENGLARD
RYAN RILEY
CHRIS ALLEN
ROBERT HAKEN
MITCHEL SELLERS
NIALL MERRIGAN
CHRIS HURLEY
RAGHAVENDRA
MATT LEE
JP TOTO
MICHAEL WILLIAMSON
TIAGO PASCOAL
2
Foreword
Michaela Murray
dotnetteam@red-gate.com
redgate
Contents
Foreword 3
Want to build scalable websites and services?
Work asynchronously 6
Where are your custom performance counters? 7
RavenDB 8
Dont call AsEnumerable on a collection before
using LINQ 9
Never call .Wait() or .Result on a Task 10
Throwing HttpResponseExceptions 11
Web API tracing 12
Message Handlers 13
Database access 14
>OLU`V\YLWYVSPUNWYLMLYHJJ\YHJ`[VKL[HPS
Make the most of connection pooling by closing
SQLConnection as soon as possible 16
OutputCache 17
<ZL*VUN\YL(^HP[[VH]VPK[OYLHKOVWWPUN
especially in library code 18
Be careful of variable allocations 20
4
How to stress test your public facing web
application using the cloud (or without it) 22
Using the keyword await doesnt make the
work asynchronous 24
+VU[\ZLHZ`UJH^HP[MVYZOVY[TL[OVKZ
Turn off Change Tracking in Entity Framework 26
Always use compiled queries in Entity Framework 27
Diagnosing JavaScript memory leaks with Chrome
Dev tools 28
Monitoring memory consumption over time 30
Use JValue in JSON.Net to parse complex JSON
objects that you dont have POCO types for 32
Cache JavaScript and CSS permanently 34
3VHKL_[LYUHS1H]H:JYPW[JVU[LU[HZ`UJOYVUV\ZS`
7YVSLKVU[ZWLJ\SH[L
More free eBooks from Red Gate 37
Tools from Red Gate 38
1
Want to build scalable websites and
services? Work asynchronously
Jeffrey Richter
www.wintellect.com
6
2
Where are your custom
performance counters?
John Robbins
'1VOU>PU[LSSLJ[^^^^PU[LSSLJ[JVT
7
3
RavenDB
David Conlin
9LK.H[LHNPSLSPRLHJH[JVT
8
4
Dont call AsEnumerable on a
collection before using LINQ
Shmuel Englard
'ZOT\LSPLISVNLUNSHYKUL[
9
A selection of tips from
Ryan Riley
@panesofglass
5
Never call .Wait() or .Result on
a Task
Never call .Wait() or .Result on a Task within your
application; it can bring your server crashing
down. It shouldnt be necessary to mention this,
but so many examples do this that its worth
reiterating.
10
6
Throwing HttpResponseExceptions
This is a very handy way to skip to the end of a
processing chain when something goes wrong. Sure,
you can return an HttpResponseMessage, but it will
pass through the filters and handlers on its way out.
Throwing an HttpResponseException skips all that
and goes right to the end. Use it with the same care
you would use in throwing any exception.
11
7
Web API tracing
Web API integrates tracing, so as to make it very easy
to know whats going on throughout the lifetime
of your services. Microsoft has released an add-
on package to enable tracing of Web API using
System.Diagnostics. You can also find adapters
for NLog and log4net on NuGet. This is really
helpful for tracking down unexpected responses
or unhandled exceptions, especially in production
applications. For the best performance, of course,
you should use Event Tracing for Windows (ETW).
12
8
Message Handlers
If you only have to handle simple cases and dont need
complex routing, you can handle a given route directly
by inheriting from DelegatingHandler and setting this
custom handler as the last parameter of config.Routes.
MapHttpRoute. This completely bypasses the filter
pipeline and requires a lot more manual work, but it also
bypasses all the Reflection-based controller and action
lookups. Heres an example:
https://gist.github.com/panesofglass/5831674.
13
9
Database access
Most examples of Web API use either Entity
Framework directly or show some abstractions such
as Repository and/or UnitOf Work, which introduce a
number of classes, as well as strong typing. Thats all
good. However, in many Web API cases youre simply
exposing, and possibly transforming, data from a
data store. You are probably reading in values from a
query string, JSON, or XML, and manipulating SQL.
All of these are strings. While you can certainly use
a serializer to work with inputs and use casting to
correctly validate data types, in many cases you can
forego the cost of boxing/unboxing or serializing/
deserializing by using dynamics. I have a gist that
shows how to do this using Dapper (with Async
support):
https://gist.github.com/panesofglass/5212462.
Use it as a way of eking out extra performance,
rather than a standard approach.
14
10
>OLU`V\YLWYVSPUNWYLMLY
accuracy to detail
Chris Allen
9LK.H[L^^^MHJLIVVRJVTJOYPZZ`MHSSLU
11
Make the most of connection
pooling by closing SQLConnection
as soon as possible
Robert Haken
'9VILY[/HRLURUV^SLKNLIHZLOH]P[Ja
16
12
OutputCache
Robert Haken
'9VILY[/HRLURUV^SLKNLIHZLOH]P[Ja
17
13
<ZL*VUN\YL(^HP[[VH]VPK[OYLHK
OVWWPUNLZWLJPHSS`PUSPIYHY`JVKL
Mitchel Sellers
@mitchelsellers
18
Consider this example using ConfigureAwait:
int numRead;
while((numRead = await
19
14
Be careful of variable allocations
Mitchel Sellers
@mitchelsellers
20
To avoid this, and reduce the size of the state-tracking
object, you could re-write the code like so:
21
15
How to stress test your public
facing web application using the
cloud (or without it)
Niall Merrigan
@nmerrigan
22
2. Coded UI Tests
The more adventurous among you can also create Coded
UI Tests (CUITs) and implement them on Azure. CUITs
can interact with the application and test parts that a
simple HTTP call cannot.
/
23
16
Using the keyword await doesnt
make the work asynchronous
Chris Hurley
Red Gate
24
17
Dont use async/await for
short methods
Chris Hurley Red Gate
Async/await is great for avoiding blocking while potentially
time-consuming work is performed, but there are
overheads associated with running an async method: the
current execution context has to be captured, there may
be a thread transition, and a state machine is built through
which your code runs. The cost of this is comparatively
negligible when the asynchronous work takes a long time,
but its worth keeping in mind.
18
Turn off Change Tracking in
Entity Framework
Raghavendra
@vamosraghava
For example:
26
AsNoTracking() is an extension method defined
on IQueryable<T>, so youll need to import the
System.Entity.Data namespace. For more details, to
understand the performance gains of AsNoTracking(),
have a look at
http://msdn.microsoft.com/en-us/library/cc853327.aspx and
http://blog.staticvoid.co.nz/2012/4/2/entity_framework_and_
asnotracking
19
Always use compiled queries in
Entity Framework
Using compiled queries on top of ObjectContext or
DBContext can significantly improve application
performance, because you save much of the time
that Entity Framework would have to spend
compiling your query to SQL.
27
20
Diagnosing JavaScript memory
leaks with Chrome Dev tools
Matt Lee
'[OH[PZTH[[NP[O\IJVT[OH[PZTH[[
28
Heres an illustration of the sort of results you can
get, using a toy example where we insert objects into
an array but never remove them:
Profiles
V I Constructor Distance Shallow Size Retamed Sue
HEAP SNAPSHOTS
~r Snapshot 1 Mu
Object 103 319 23%
109 000 22%
1259108 13%
1200 090 1* %
1795309 18
1290090 12%(I
-
RedOate.Bar 109 000 22% 1200 090 12%' 1290 090 12%
' 20M0 RedCate.Foo 109900 22% 1200 090 12% | 1290 090 12%
Snapshot 2 Isysteiil 19913 0% 300 310 <- 659 256 7%
x 42140
larrayl 9032 2% 2 755 224 29% 2HI540 29%
Snapshot 3 Rlstnng) 9953 2% 210972 2% 217 012 2%
O
> var 1 ; var a
-
Summary
[); while (--)
All objects
> var 1< hle ( --) < a.push(nea RedGet e. Foo) >;
>
Ot >2 Q, Q ctop frame > <page context > Errors Warnings Logs Debug 0
29
21
Monitoring memory consumption
over time
Matt Lee
'[OH[PZTH[[NP[O\IJVT[OH[PZTH[[
MEMORY
USE
TIME
30
MEMORY
USE
TIME
MEMORY
USE
IMAM TIME
31
22
Use JValue in JSON.Net to parse
complex JSON objects that you
dont have POCO types for
JP Toto
@jptoto
32
using Newtonsoft.Json.Linq;
dynamic json = JValue.Parse(response_string);
foreach (dynamic something in json)
{
string name = something.name;
int count = Convert.ToInt32(something.total);
33
23
Cache JavaScript and
CSS permanently
Michael Williamson
TPRLa^VIISLVYN
34
24 nt ent
pt c o
a Sc ri
av
t e r n al J
o a d ex nously
L
y n c hro amson ur
as Willi
ael LVYN ing s
lo w ly, yo
i c h
M a^VIIS i s lo a d
final
ly
i t e s i te
TPRL
al s erna
l
ex tern e x t
an he
w i s e, if l l u ntil t
r ta d
Othe ge will s b e loade t
pa . t ha
own s loading t h a t can nippet t
he g ts
finis o m ethin n adver instead.
s a
clu ding nstance, n iframe
i n i a
ure , for it in
If yo ronously ite, put
ch r
asyn u m ent.w
doc
uses
25
7YVSLKVU[ZWLJ\SH[L
Tiago Pascoal
pascoal.net
36
More free eBooks from Red Gate
3UDFWLFDO3HUIRUPDQFH3UROLQJ
,PSURYLQJWKHHIFLHQF\RI1(7FRGH
by Jean-Philippe Gouigoux
1(73HUIRUPDQFH7HVWLQJDQG2SWLPL]DWLRQ
by Paul Glavich and Chris Farrell
8QGHUWKH+RRGRI1(70HPRU\0DQDJHPHQW
by Chris Farrell and Nick Harrison
Chris Farrell and Nick Harrison take you from the very
basics of memory management, all the way to how the
OS handles its resources, to help you write the best code
you can.
37
Tools from Red Gate
$1763HUIRUPDQFH3UROHU
Identify bottlenecks and optimize the
performance of your application.
$1760HPRU\3UROHU
Find memory leaks and optimize the memory
usage of your application.
D 1(75HHFWRU
Browse, analyse, decompile, and debug your
.NET code.
6PDUW$VVHPEO\
.NET obfuscator to protect your IP; plus, Error
Reporting functionality to help you ship stable
software by getting early user feedback.
6 1(7'HPRQ
.NET Demon compiles your code continuously,
so you see errors as soon as they are introduced.
38