hi,
do you know where i can find some ebooks or websites talking about C#
optimisation ?
for exemple, i just learned that ++i is faster than i++. i would like to
know more about the things that can make code faster than fast.
thank you.
Nov 17 '05
55 3737
"Never use foreach loops" -- that advice is specific to the collection.
ArrayList used a class for an enumerator, so it is slower that way. But if
you implement your enumerator as a struct the foreach loop is as fast as the
indexer loop, when creating your own array-list type.
The standard design guideline from Microsoft now is to use a struct for an
enumerator type. This came as a result of experience with ArrayList. This is
another example where a struct must be mutable for performance.
Regards,
Frank Hileman
check out VG.net: http://www.vgdotnet.com
Animated vector graphics system
Integrated Visual Studio .NET graphics editor
"Clint Herron" <Cl*********@di scussions.micro soft.com> wrote in message
news:A8******** *************** ***********@mic rosoft.com... If your app isn't performing well enough, get a profiler and find out exactly where the bottleneck is. At that point, and only at that point, should you be really worried about micro-optimisations.
Haven't you ever noticed C# doing funny things though?
For instance, in profiling that I've done for my components, I've noticed a *severe* performance hit when I use "this.metho d()" instead of just "method()". You wouldn't think it would be significantly slower, but it really seems to be from my profiling tests.
Another way to make your code faster is to never use foreach loops.
foreach (someObj obj in myArrayList) obj.method()
can be performed much faster if done as:
for (int cnt = 0; cnt < myArrayList.Len gth; cnt++) ((someObj) myArrayList[cnt]).method()
I think that's the sort of micro-optimizations he's asking for.
I, too, would be interested in such a list if anyone knows of one.
There's more than one way to do it, but unfortunately, so many of the possible ways are very bad. I want to know the *right* way to do something, and I've found very little information on how to do it.
--clint
Hey Jon! Thanks for the reply! Haven't you ever noticed C# doing funny things though?
For instance, in profiling that I've done for my components, I've noticed a *severe* performance hit when I use "this.metho d()" instead of just "method()". You wouldn't think it would be significantly slower, but it really seems to be from my profiling tests. Could you post a short but complete program which demonstrates that?
See http://www.pobox.com/~skeet/csharp/complete.html for details of what I mean by that.
Hrm. You know, I can't reproduce this right now. That's odd. I'm sure I saw
performance hits on my code, and noticed a significant improvement in my
profiler runs when I changed this before.
It might have had something to do with inherited classes, but I dunno'.
Okay, well you got me on this one, I can't show it right now. Hrm. I'll keep
stewing on this one.
I wouldn't expect the binaries to be any different at all.
Another way to make your code faster is to never use foreach loops. Not significantly, IME.
What exactly do you mean by "much" faster?
On the order of 250% (my results right now are showing around 278%)? Would
you consider that significant?
For instance, I have an application where I'm calculating high resolution
phase and magnitude response curves in real-time, so I've got thousands of
data points that I'm looping through at 15-20 fps -- so spending a lot of
unnecessary time on MoveNext is a big deal to me.
Here's a small sample app:
using System;
using System.Collecti ons;
namespace SpeedTest
{
class MainClass
{
public static void Main(string[] args)
{
ArrayList randVals = new ArrayList(10000 00);
Random myRand = new Random();
for (int cnt = 0; cnt < 1000000; cnt++)
randVals.Add (myRand.Next()) ;
int minVal = 0;
System.DateTime Time1;
System.DateTime Time2;
System.DateTime InitTime = System.DateTime .Now;
for (int cnt = 0; cnt < 100; cnt++)
minVal = Min1(randVals);
Console.WriteLi ne("Min value is: " + minVal.ToString ());
Time1 = System.DateTime .Now;
for (int cnt = 0; cnt < 100; cnt++)
minVal = Min2(randVals);
Console.WriteLi ne("Min value is: " + minVal.ToString ());
Time2 = System.DateTime .Now;
System.TimeSpan TimeEl1 = Time1 - InitTime;
System.TimeSpan TimeEl2 = Time2 - Time1;
Console.WriteLi ne("First search took: " + TimeEl1.ToStrin g());
Console.WriteLi ne("Second search took: " + TimeEl2.ToStrin g());
}
public static int Min1(ArrayList vals)
{
int currentMin = (int) vals[0];
for (int cnt = 0; cnt < vals.Count; cnt++)
if ((int) vals[cnt] < currentMin)
currentMin = (int) vals[cnt];
return currentMin;
}
public static int Min2(ArrayList vals)
{
int currentMin = (int) vals[0];
foreach (int curVal in vals)
if (curVal < currentMin)
currentMin = curVal;
return currentMin;
}
}
}
The right way to do something is the most readable way - look how much more readable it is to use foreach than to use the for loop. Very, very few applications have bottlenecks due to this kind of usage rather than algorithmic or IO-based bottlenecks.
*shrug*. When profiling with NProf, I notice a lot of time is spent going to
collection indexers for MoveNext(), when I could just be incrementing a
counter and going to the next index.
I agree -- I like the way that foreach looks also, but when I notice a
significant performance hit when I use foreach, I need to optimize. I wrote
everything with foreach when I was starting, and then moved away from it
after everything was working and the boss was complaining about speed issues.
It's frustrating to me that not more information is readily available about
such optimization issues.
BTW, for those who don't want to run the program, here were my results
(repeatable and irrespective of which search went first):
Min value is: 1669
Min value is: 1669
First search took: 00:00:01.232300 1
Second search took: 00:00:03.436414 1
Respectfully,
clint
Clint Herron <Cl*********@di scussions.micro soft.com> wrote: Could you post a short but complete program which demonstrates that?
See http://www.pobox.com/~skeet/csharp/complete.html for details of what I mean by that. Hrm. You know, I can't reproduce this right now. That's odd. I'm sure I saw performance hits on my code, and noticed a significant improvement in my profiler runs when I changed this before.
It might have had something to do with inherited classes, but I dunno'. Okay, well you got me on this one, I can't show it right now. Hrm. I'll keep stewing on this one.
I'll believe it when I see it :) I wouldn't expect the binaries to be any different at all.
Another way to make your code faster is to never use foreach loops.
Not significantly, IME.
What exactly do you mean by "much" faster?
On the order of 250% (my results right now are showing around 278%)? Would you consider that significant?
Only if i do virtually nothing in loops with 100,000,000 iterations
(effectively) like you are in your test case. I very rarely have a loop
where the iteration is actually the bottleneck.
Note that using an array rather than an array list would take the time
down by a factor of 10, and then foreach is faster...
For instance, I have an application where I'm calculating high resolution phase and magnitude response curves in real-time, so I've got thousands of data points that I'm looping through at 15-20 fps -- so spending a lot of unnecessary time on MoveNext is a big deal to me.
You'd be better off using an array then, at which point the more
readable solution is roughly the same speed as the solution using a for
loop, and much faster than using an ArrayList.
For most apps, however, loops aren't as trivial as the one you posted,
and the bottleneck isn't in iteration.
Even if it *is* in an iteration, it tends to be localised - it's worth
considering micro-optimisations *only* when you've found the
bottleneck. The right way to do something is the most readable way - look how much more readable it is to use foreach than to use the for loop. Very, very few applications have bottlenecks due to this kind of usage rather than algorithmic or IO-based bottlenecks.
*shrug*. When profiling with NProf, I notice a lot of time is spent going to collection indexers for MoveNext(), when I could just be incrementing a counter and going to the next index.
I agree -- I like the way that foreach looks also, but when I notice a significant performance hit when I use foreach, I need to optimize. I wrote everything with foreach when I was starting, and then moved away from it after everything was working and the boss was complaining about speed issues.
And that's the time to find the bottleneck, and optimise *just* there.
Everywhere other than the bottleneck should use the most readable code.
It's frustrating to me that not more information is readily available about such optimization issues.
BTW, for those who don't want to run the program, here were my results (repeatable and irrespective of which search went first):
Min value is: 1669 Min value is: 1669 First search took: 00:00:01.232300 1 Second search took: 00:00:03.436414 1
My results weren't quite as bad as those - about the same time for the
first search, but always under 3 for the second.
--
Jon Skeet - <sk***@pobox.co m> http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Hey Jon! It might have had something to do with inherited classes, but I dunno'. Okay, well you got me on this one, I can't show it right now. Hrm. I'll keep stewing on this one. I'll believe it when I see it :)
hehe, okay. :) For instance, I have an application where I'm calculating high resolution phase and magnitude response curves in real-time, so I've got thousands of data points that I'm looping through at 15-20 fps -- so spending a lot of unnecessary time on MoveNext is a big deal to me.
You'd be better off using an array then, at which point the more readable solution is roughly the same speed as the solution using a for loop, and much faster than using an ArrayList.
Touche', I'm actually using an array. Sry.
However, I will note that MoveNext() takes up a fair chunk of time in my
profile, just from everywhere else I'm using ArrayLists. Granted, it's called
millions of times, but still, it's time.
And that's the time to find the bottleneck, and optimise *just* there. Everywhere other than the bottleneck should use the most readable code.
Good call, and yeah, I'll agree with you there.
"Premature optimization is the root of many evils."
However, sometimes this can go overboard. One good example is hashtables,
vs. and array with an enumerated indexer.
Question:
is
MyCollection["Name"]
more readable than
MyCollection[DataFields.Name]
?
Answer:
Slightly, yes.
But hashtables take an enormous amount of overhead, and using an enumeration
isn't that much more confusing (plus it can help prevent typos regarding
mispelling the index).
Overall though, I think you're right on everything that you've been saying.
But when I am coding for speed, I would like to know some of the little
things that I can do to speed stuff and generate cleaner code. Min value is: 1669 Min value is: 1669 First search took: 00:00:01.232300 1 Second search took: 00:00:03.436414 1
My results weren't quite as bad as those - about the same time for the first search, but always under 3 for the second.
Heh, you should have seen it before I tweaked the numbers -- I was getting
*long* run times, and almost crashed my computer. After I finally regained my
desktop (thankfully didn't have to restart -- yay for managed code!), task
manager said that my memory usage peaked out at one point at 1.5 gigs --
phew! It was chuggin'. :)
Thanks again! It's been very nice chatting with you, Jon.
Respectfully,
clint
Clint Herron <Cl*********@di scussions.micro soft.com> wrote:
<snip> Thanks again! It's been very nice chatting with you, Jon.
Likewise - sounds like we're pretty much on the same page :)
--
Jon Skeet - <sk***@pobox.co m> http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
> For instance, in profiling that I've done for my components, I've noticed
a *severe* performance hit when I use "this.metho d()" instead of just "method()". You wouldn't think it would be significantly slower, but it really seems to be from my profiling tests.
I have tested this, and there is absolutelly no difference in IL generated
for this.Method() calls and for Method() calls.
in first case, I have used
this.Initialize Component();
and in the other, I have used just
InitializeCompo nent();
the generated IL looks absolutely the same in both cases.
..method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 20 (0x14)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldnull
IL_0002: stfld class [System]System.Componen tModel.Containe r
ThisDotTest.For m1::components
IL_0007: ldarg.0
IL_0008: call instance void
[System.Windows. Forms]System.Windows. Forms.Form::.ct or()
IL_000d: ldarg.0
IL_000e: call instance void
ThisDotTest.For m1::InitializeC omponent()
IL_0013: ret
} // end of method Form1::.ctor
there is also no way to indicate this.Method() against Method() when writing
IL code, of course ;-)
Where is your *severe* performance hit?
Sincerely,
Lebesgue This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: OPQ |
last post by:
Hi all,
I'd happy to have you share some thougts about ultimate optimisations
on those 2 topics:
(1)- adding one caractere at the end of a string (may be long)
(2)- in a dict mapping a key to a list of int, remove every entrie
where the list of int have of length < 2
|
by: Simon Elliott |
last post by:
What optimisation do compilers typically provide when passing STL
containers around?
For example, if I do something like this:
struct Tbloggs
{
std::string s1;
};
typedef std::vector<Tbloggs> TbloggsList;
|
by: simonwittber |
last post by:
Hello People.
I've have a very tight inner loop (in a game app, so every millisecond
counts) which I have optimised below:
def loop(self):
self_pool = self.pool
self_call_exit_funcs = self.call_exit_funcs
self_pool_popleft = self.pool.popleft
self_pool_append = self.pool.append
|
by: EC-AKD |
last post by:
Hi All,
I am new to the concept of optimising codes in C. I was wondering if
C level inlining of code is any way comparable to macros. I believe
that inlining is equivalent to writing macros. However I had this
strange feeling if I should go for macros wherever necessary instead
of inlining the codes.
In my project, I have to use basic operations like add and sub many
times. So I initially inlined them and found a lot of optimisation.
|
by: Jon Maz |
last post by:
Hi,
I'm facing a code-optimisation issue on an asp.net/vb.net/SQL Server 2000
project. A web page containing not much more than 3 DropDownLists is taking
nigh on 6 seconds to load, because each ddl opens up a separate connection
to the DB, pulls out its data, and closes its own connection before the next
ddl repeats the process.
The code to handle each DDL's connection to the DB is packaged in an object
(presentation-layer code...
| |
by: Lee Harr |
last post by:
I have a database where I remove the schema public. When I
try to use the createlang script, it fails like this ...
>createdb foo
CREATE DATABASE
>psql foo -c "select version()"
version
---------------------------------------------------------------------
PostgreSQL 7.4.1 on i386-portbld-freebsd4.9, compiled by GCC 2.95.4
(1 row)
|
by: David Welch |
last post by:
Hi,
I have a bit of code where I am relying on empty base member
optimisation. The bit of code is below:
template<typename Enum>
struct EncodePrefix
{
template<Enum e>
struct Apply
|
by: grid |
last post by:
Hi,
I was exploring the affect of cache on program
performance/optimisation.Is it the compilers responsibility only to
consider this kind of optimisation or the programmer can do his bit in
this case ?
Reading through the "Expert C Programming" text,it mentions how the
below program can be efficient taking the cache details into accont.
The below program can be executed using the two versions of copy
alternatively and running the time...
|
by: special_dragonfly |
last post by:
Hello,
I know this might be a little cheeky, and if it is, please say, but I need a
little hand optimising some code. For the simple reason that this is
'company' code and I have no idea what I'm allowed to release and not as the
case may be I've changed anything that could give an indication of the
company - if that makes any sense...
for the code below:
text_buffer is a single record from an XML stream. I can't read in the
entire XML...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |