Freewind
Freewind

Reputation: 198318

The performance of `unsafe` in Java and C#

I'm trying to learn digital image processing, I found my friend using c#. There is a very important reason why he using C#: There is unsafe keyword in c# and the performance of his code(algorithm part) can reach 75% of same code in c++, which is good enough for him.

He encourages me to turn to c#, but I'm java programmer of many years. I know there is a Unsafe class in java too, but I have never used of it, not sure if the performance is as good as C#.

So I want to know the performance of Unsafe in java, and is it a good idea to use Java for image processing?


UPDATE

Just using unsafe code for some performance-aware task, not use it everywhere.

Upvotes: 2

Views: 2137

Answers (3)

Tony Hopkinson
Tony Hopkinson

Reputation: 20320

Unsafe means you can avoid all the overheads in a managed environment. All the range and type checking, Garbage collection, reflection etc. Whether your code will be faster using unsafe all depends on what you wrote. I dare say the main optimisation point would be processing large blocks of raw memory as opposed to say a list of pixel classes or structs which OO would lead you towards.

Upvotes: 3

walther
walther

Reputation: 13600

I love C#, but choosing one language over another because of a feature, that has a very limited scope seems a very weak argument to me. Don't pick a language based on your friend's opinions, but based on your needs and preferences! Programming language is just a tool. You'd seriously dump years of experiences just like that? Use the language you're most comfortable with.

Upvotes: 2

exexzian
exexzian

Reputation: 7890

Check this discussion it comes up with both plus and negative points about it here

Though this one taken from C# article but I think it applies well for Java too - check here In unsafe code or in other words unmanaged code it is possible to declare and use pointers. But the question is why do we write unmanaged code? If we want to write code that interfaces with the operating system, or want to access memory mapped device or want to implement a time critical algorithm then the use of pointer can give lots of advantages.

But there are some disadvantages of using pointers too. If pointers were chosen to be 32 bit quantities at compile time, the code would be restricted to 4gig of address space, even if it were run on a 64 bit machine. If pointers were chosen at compile time to be 64 bits, the code could not be run on a 32 bit machine.

Upvotes: 0

Related Questions