Speeding up the execution of C#/.NET application [closed] - c#

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I'm searching for methods to boost up C#/.NET application.
What I found so far is
Use ngen.
Careful when using as operator
Careful when using reflection API. It takes quite a while to load dll with Assembly.LoadFrom().
What else tools/tips/good practices do you have to get the best performance out of C#/.NET program.

First be careful with ngen. It might actually end up hurting performance. See Jeff Richter's book "CLR via C#, Third Edition" for more details.
Personally I will use a profiler when I need to performance tune my application. The one I prefer is Red-Gate Ants, but there are plenty of good ones on the market. However using these can be a bit tricky because they will produce a lot of noise.
Most of the problems I have seen are usually caused by the developer or overall architecture rather than the .Net Framework. For example an Asp.Net web application that requires 30+ calls to the Database just for the home page to load.

Memoize expensive functions when possible.
public static class Expensive
{
private static readonly ConcurrentDictionary<int, int> _map =
new ConcurrentDictionary<int, int>();
public static int Calculate(int n)
{
return _map.AddOrUpdate(n, Add, (key, value) => value);
}
static int Add(int key)
{
return 0;
}
}

You should not use ngen until you precisely know what CPU environment your dlls are going to be deployed on. And know for sure that they will not be deployed on other CPU types. It is bad if you compile to x86 native and deploy on x64. You will lose all the optimizations the compiler could have done JIT.
Performance depends on what your application is trying to do. The guidelines would be very different if it was a db driven web app vs a desktop music player app. But you should be looking to avoid boxing/unboxing, lots of reflection, using XmlDocument to load up a very large Xml doc, and use the inbuilt CLR ThreadPool class to do multi-threading, remember to implement IDisposable to name a few..

I once spent several days rewriting code to speed up the application, when in fact I found out there was a bottleneck in my CompareTo implementation which was being called thousands of times.
Use a profiler.
Don't waste time optimizing what doesn't matter (in your case).
Find out what does.

Related

Client in C++, Server in C# [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I'm creating a MMO game. I will be using TCP client/server communication. At first my approach was to write both client and server in C++, but now I'm starting to think if it wouldn't be easier to write server in C#.
Client is going to be written in C++ because it needs to be cross-platform, but server will always be on Windows system. I consider choosing C# because it has an easier way of handling threads, built-in XML parser, etc.
My question is if it would be a good solution? Performance is still important to me, so if choosing C# over C++ would have a drastic influence on performance, I'd stick with C++.
Also if you think it's good idea, do you know if there are any tutorials that present communication between C# server and C++ client?
Thanks in advance for answers.
The performance difference between C++ and C# is not as large as you might think.
For the communications, if you're bothered about performance, use sockets and something like Google Protocol Buffers or Thrift. If you're less bothered about performance, use HTTP and JSON or XML.
Using different languages for client and server forces you to rewrite quite a bit of things in separate languages I would personally want to keep in sync:
Serialization and deserialization, although you could of course use some library for that. Google Protocol Buffers come to my mind, as they are explicitly designed to save bandwith and work "cross language".
Almost every entity of your game will have a more or less common set of properties. When going with different languages, you would have to keep these in sync manually and probably write them twice. This is especially annoying with more complex setters ;)
You will want to have some shared logic to "emulate" server answers on the client. Its important to predict on the client side what the server does to get a "snappy" behaviour. And what could emulate that behaviour better then using the same codebase for server and client?
I would't see a great problem with performance when using C# on the server though. That shouldn't be an aspect that strongly influences your decision.

what optimizations can I do to run C# program faster? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I'm writing trading software and I need every single microsecond in speed.
What can I do? I was thinking to use ngen but wikipedia tells that JIT might be even better. What can I tune? May I force it to use Xeon E5 instructions somehow? Will changing priority in Windows to highest help and if so how to run program always with highest priority? May I add this program to "trusted" so .NET will not check security etc.
I.e. I want complete list of configurations in hardware/software/.net and actions (like running ngen) which can affect and help run program faster.
The time comes stop guessing and find where the problem(s) actually are.
Use EQATEC free preformance analyzer to figure out your bottlenecks and fix them.
NGEN is usefull to boost the startup time of the application , but it's definitely not a golden key for that problem. It's most probabble that you will fix it profiling your app.
What about runtime optimization:
checkout DB accesses (if any), optimize your queries and minimize the data retrived to the amount you really need
look on disk access operations
look on CPU consuption. After profiling yoi can use Process Explorer to check CPU and Memory consuption from your application behavioural point of view
after profiling identify unnecessary or heavy iteration you made (if any), and make use of dictionary (just example) for O(1) access
... and more...
Like a literature for reading on performance can suggest definitely the monster blog of one of the greatest performance specialists in IT industry: Rico Mariani's Performance Tidbits
Hope this helps.
Not windows, pick a more real-time focused OS, as speed has several components, consistent speed or best possible?
Tuning code is nice and all, but don't always go for that. Try code reviews, correcting large logical errors or extra work is much more beneficial than low level tuning.
Understand that every microsecond counts, but your CPU and logic are the fastest part, network, disk, paging, etc are more than likely the real enemies. So make sure you are focusing on the right thing. You must stop all I/O which is not needed.
Certain drivers, network cards, etc are faster than others.
Review your use of libraries and make sure you understand their performance aspects, so much run time is within libraries etc.
Sure there are more .NET centric answers and specific ones, but I tried answering the question behind the question.
Eliminate GC!
Another "trick" that people use is in trading systems is to write C# code that does not garbage collect. Obviously it is impossible to remove garbage collection entirely, but what you can do is minimize or eliminate GC once your program is running. You do all the work to setup your app, initialize your components, etc in an initialization phase and allow any GC here. But once you are setup and ready to run, you make sure that the code does not generate garbage and does not perform boxing/unboxing. (Have a search on SO for like "avoid GC" and you will find some useful information).
The term "trading system" can encompass a myriad of different things. Are you talking about writing an algo in .NET? Or is your algo written in something else and there is .NET framework that is hosting it? Are you just talking about the UI? Is your trading system distrubuted? Do you know how fast you program needs to be? If you are not trading a High Frequency model then what is "fast enough"? Don't just push for something that has to operate in the 1-2ms scale when your trading strategy does not need it.
And importantly, don't throw out the tried and trusted OO principles; SOLID still applies to trading systems although you may bend the rules in certain cases. Just make sure that you identify what needs to be performant and optimize that - don't think that you have to optimize everything and make sure you benchmark and measure everything so that you know what needs to be faster and by how much.
And Keep It Simple! A trading system does not have to be complex.

Converting a C# engine into C++ for speed [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
So this is the situation right now:
I have a C# GUI project combined with a C# Engine project in the same solution. The GUI allows interaction with the user, some high level stuff etc. The functionality of the Engine is to communicate with another third-party application. The Engine has sockets that connect to the third-party application as well has methods to convert a message into an object, send it to the third-party application, and listen for a response from the third-party application and react accordingly. Data to be communicated between the Engine and the Third-party application are packaged into objects.
The problem with the C# engine is that it's too slow. So the idea is to convert the engine to unmanaged C++ for speed.
This is my plan of attack:
Translate the entire C# engine by hand into C++ (which is already pretty daunting because the C# engine includes threads and hashtables)
Have the following to substitute for constructors, accessors, and mutators in C++:
void* CreateInstance()
{
MyClass* p = new MyClass();
return p;
}
void ReleaseInstance(void* pInstance)
{
MyClass* p = (MyClass*)pInstance;
delete p;
}
int GetData(void* pInstance)
{
MyClass* p = (MyClass*)pInstance;
return p->GetData();
}
void SetData(void* pInstance, value)
{
MyClass* p = (MyClass*)pInstance;
p->SetData(value);
}
(The reason why I can't use real classes in C++ is because you can't instantiate C++ objects in C#)
Then build a C++ unmanaged DLL, use P/Invoke within the C# GUI project ([DllImport etc.]) to access all the C++ methods, and use that to replace the C# engine. Objects will be simulated using methods and passed back and forth between the C# GUI and C++ Engine.
Before I embark on this time-consuming task, is there any C# code that would be impossible to translate into C++ and then re-imported back into the C# GUI through this method?
There's not going to be any C# code that's impossible to translate into C++. You might want to look into if there are any library functions in .NET that aren't covered by the C++ libraries you'll be working with, though. Make sure you aren't getting stuck with any wheels to reinvent.
That said, in my practical experience real-world C++ code is not naturally faster than real-world C# code. It's true that a C++ programmer has more available tricks that can allow them to get better performance, but the effort involved in getting to that point can often be quite formidable. Consider the famous case of the competition between Rico Mariani and Raymond Chen. The advantage Chen's final version enjoyed over Rico's was ultimately down to just the time the .NET run-time needed to bootstrap itself. That's a bit of overhead that's negligible for a longer-running process.
So I would strongly encourage you to try spending some time with a performance profiler to see why the C# code is slow first, and what you can do to speed it up. It may very well be that by going that route you can get the code running fast enough for your needs with a fraction of the effort. It's amazing how impressive you can look just selecting better data structures.

Which is faster for writing files C# (.NET) or PERL? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
We have a lot of old legacy Perl scripts that connect to a MS SQL db process some records, and make files. Over time, the daily transaction size grew and these scripts are becoming more and more expensive.
Moreover, the Databases grew with more and more tables, and modifying the old Perl scripts is cumbersome. Was thinking about redoing some of the major scripts under .NET (in C#)
Is there a speed advantage under a machine running Windows Server of using one vs the other?
Again the idea is
Execute Query
Process Results through some basic formatting
Write results to a file
Depends on how stupid the respective programmers are. When initialized properly they both should be comfortable saturating whatever bandwidth you throw at them disc system wise - and THERE is your bottleneck. Make large cached writes (.NET BufferedStream) and make ure you have a SSD or something fast ready. The perforamcne bottleneck with proper programming is the disc subsystem for this type of work.
Both tasks can be done equally fast in either language. They can also both be done horribly wrong and horribly slowly in both languages, so there is that to consider.
From another one of your comments, you mention that you do the formatting on the SQL server side. These queries would potentially be a lot less expensive if you did that on the app side, and then moved this script to a faster machine so as to impact the db server the least.
I'd guess that harddrive speed is your biggest problem now. You should monitor the resources while running this script -- Is it maxing out your cpu? is it reading/writing a lot to memory?(it shouldnt). Is it just waiting on disk i/o most of the time? If it is, you should look into upgrading your storage to either faster disks, a raid, or an ssd depending on what makes the most sense for your situation.
Even just something like defragging the disk might help.
If you have good cpu/memory to spare but cant avoid the slow disk, you could even look into compressing all of the output in memory before writing it (again, assuming this is a good idea, it really depends on where these reports are going and what format is needed).
I don't expect great differences between those languages when it comes to write performance (generally bottleneck will be hard disk, not processing power of CPU) . You should rather take a look on "costs of maintaining code", in C# you can get much cleaner code, not to mention that integration with MS SQL probably will be more efficient, not to mention that you can use threading.
Better Code, more maintainable, maybe faster. Yeah C# is good idea

OS(Operating System) Programming in C# [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I know this project.The question is that "Can we create a real OS with Managed Code or the os that will create with this project is a hello world os?"
Operating Systems need to have full control on hardware.Can we do it with this one?
If there are any another project please tell me
Cosmos Project
Yes it can be done - see Singularity which is (was) a Microsoft research project to create an entirely managed operating system in "Sing#" (an extended version of "Spec#" which is itself an extension of C#). Its worth stressing that this was just a research project into the concept, and was never intended as a "full" operating system of the likes of Windows or Max OSX.
The source code is available on CodePlex - you can download the code, build it and run it yourself in an emulator (I've done it myself, its well documented and relativley easy although I can't remember the exact steps myself).
Parts of the system were written in assembly / C, specifically the bootloader and the lowest level x86 interupt dispatch code however this is essentially all but unavoidable (it is by its very nature very platform dependant - something needs to write the x86 instructions to control and respond to basic hardware). The low level interrupts are also not particularly interesting in terms of how the operating system actually functions, so I personally don't consider this as cheating the "entirely managed" definition.
Looking on the Wikipedia page for Singularity there are also 5-6 similar projects, including Cosmos and a couple of similar attempts that use Java instead of C#.
The focus of Singularity OS was on security and dependency, however whats also impressive is that according to some basic benchmarks in An Overview of the Singularity Project1 (PDF) the performance of their archetecture was actually comparable to that of other "more conventional" operating systems:
... these numbers demonstrate that architecture that we
proposed not only does not incur a performance penalty, but is often as fast as or faster than more
conventional architecture. In other words, it is a practical basis on which to build a system.

Categories