The performance of `unsafe` in Java and C#

烂漫一生 提交于 2019-12-11 03:21:02

问题


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.


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/11914818/the-performance-of-unsafe-in-java-and-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!