Can using non primitive Integer/ Long datatypes too frequently in the application, hurt the performance?

前端 未结 4 1681
孤街浪徒
孤街浪徒 2021-01-20 11:02

I am using Long/Integer data types very frequently in my application, to build Generic datatypes. I fear that using these wrapper objects instead o

4条回答
  •  野的像风
    2021-01-20 11:49

    Repeat after me. "Creating an object in Java is not an expensive operation".

    You are prematurely optimizing your application. A better approach is to implement it in the natural way using Integer and Long, then profile it to determine where the bottlenecks are. If the profiler tells you that use of Integer and Long is a performance issue, then look at ways to cure this.


    If you determine that Integer and Long really are an issue, here are some things you could do:

    • Look for a class library that implements "collections" of primitive types; e.g. Trove. But beware that the APIs of such collection types won't be compatible with java.util.Collection and its descendants.

    • Use Integer.valueOf(int) and Long.valueOf(long) rather than new Integer(int) and new Long(long). The valueOf methods use a cache of frequently used objects to reduce the number of object creations.


    @Rex Kerr's comment is that this is horrible advice. He is (I think) saying that the OP should optimize his application to reduce the use of Integer and Long before he knows that this will be a performance concern. I disagree.

    • At this point (when he asked the question), the OP didn't know that his application needed optimization. If the application runs "fast enough" without any optimization, then any developer time spent optimizing it would be better spent on something else.

    • At this point, the OP doesn't know where the performance bottlenecks are. If they are not in the handling of these values, then optimizing this aspect will be a waste of time. Note that generally speaking it is a bad idea to rely solely on your intuition to tell you where the bottlenecks are or are likely to be.

    • @Rex Kerr posits that it would be a lot of work to modify/restructure the code to fix performance issues due to over-use of Integer and Long. That's simply not true. A decent IDE makes it easy to make this sort of change in a small to medium size application.

提交回复
热议问题