wrapped Longs to this list
queryParms.add(new Long(empRec));
I am using JDK 1.5 and using wrapped longs to a list. My Boss was yelling at me开发者_开发问答 seeing this.
Is it a good approach? Does it impact in terms of performance. What should be alternative?
It is unnecessary to do this. Java does it automatically with autoboxing.
In short - collections don't accept primitives. So whenever you call collection.add(longVar)
it is automatically translated to collection.add(Long.valueOf(longVar))
Another thing - don't use the constructor new Long(..)
even in cases where autoboxing doesn't work. Use Long.valueOf(..)
- it first looks in a cache of Long
instances. From the documentation of Long.valueOf(..)
:
If a new Long instance is not required, this method should generally be used in preference to the constructor Long(long), as this method is likely to yield significantly better space and time performance by caching frequently requested values.
You should let autoboxing get that for you. You should read the examples in "Autoboxing and Auto-Unboxing of Primitive Types".
Resources :
- Autoboxing support for the Javatm Programming Language
The alternative is to take advantage of autoboxing:
queryParms.add(empRec);
But I'd ask your boss why he's yelling at you. This really doesn't seem like the kind of thing to have a conniption over. Maybe his caps lock key is broken? :P
Using autoboxing will save you typing as other answers have mentioned; however using autoboxing vs the way you have done it have the same performance; the difference is only in readability.
If you want to store numbers in a list, and you don't know how many you're going to need, this is a good approach. It is easy to read, and more complex pieces of code are more likely to have bugs.
If you know exactly how many items you want to store, you could create an long[]
and put the numbers in there. You save the necessity to create/get Long
objects for each element.
However, before looking to change the piece of code you wrote into something more complex, e.g. long[]
or something else, be aware that most pieces of code do not impact overall application performance. E.g. in one user request, if you are doing some database work, reading/writing some files, doing some network activity, and writing 10 numbers into a List<Long>
, then the performance of the request will be determined by those other factors, which will take 1000x or more time than creating the list. If performance is a problem, then optimizing something that takes less than a 1000th of the total time will not make any noticeable difference to the time the entire request takes.
精彩评论