How to instantaneously convert array of Integers into an array onint's?

R

Royan

Assume I have an array of Integer objects and I need to convert them
into primitive *int* array. Another problem is that I need to this
really fast, so is there anything better then a *for* loop?
 
A

Alan Morgan

Assume I have an array of Integer objects and I need to convert them
into primitive *int* array. Another problem is that I need to this
really fast, so is there anything better then a *for* loop?

There are three ways to optimize something:
1. Do it faster
2. Don't do it as often/at all
3. Don't worry about it

#2 and #3 are my favorites. Generally speaking, you'll reap more benefits
by changing things so that you don't have to call function A than you will
by making function A run faster. Why are the integers boxed in the first
place? Why do you have to have unboxed ints? Have you actually profiled
to make sure that this bit of code is actually the slow bit? If it
absolutely, positively, has to be as fast as possible then have you
considered rewriting in another language? Duff's Device will probably
make the code run faster, but I'd be very suspicious of anyone who actually
used it. Java does bounds checking on arrays. If the array is very large
then you *might* see a win by going to JNI, but I wouldn't even bother
with this unless the array size were in, oh, I don't know, millions of
entries.

Alan
 
R

Roedy Green

Assume I have an array of Integer objects and I need to convert them
into primitive *int* array. Another problem is that I need to this
really fast, so is there anything better then a *for* loop?

I think the fastest code you will come up with is:
int n = to.length;
for (int i=0; i<n; i++)
{
to = from;
}
leave it to auto-un-boxing to select the optimal conversion function.
 
M

Mike Schilling

Alan said:
Duff's Device will probably
make the code run faster, but I'd be very suspicious of anyone who
actually used it.

It's actually not legal in Java. I can't quote you chapter and
version, but I do recall this being pointed out in the JLS with the
aside "Sorry, Tom".
 
L

Lew

rossum said:
What about:
for (int i = 0, final int n = to.length; i < n; ++i) {

- scope of n is more restricted restricted so may help the compiler.
- "final" may allow the compiler to optimise more.
- pre-increment is never slower (and sometimes faster) than
post-increment. Though in this case it probably will not matter, it is
a good habit to get into.

Have you attempted to explore that induction?

--
Lew



- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Sometimes, Washington is one of these towns where the
person -- people who think they've got the sharp elbow
is the most effective person."

--- Adolph Bush,
New Orleans, Dec. 3, 2002 (Thanks to Michael Shively.)
 
R

Roedy Green

If the array is very large
then you *might* see a win by going to JNI,

To elaborate, the problem with JNI is there is such a penalty for
crossing the blood-brain barrier that you eat up any savings you get
from faster code on the C++ side.

see http://mindprod.com/jgloss/jni.html

It is a bit like going to Mexico for the cheap oranges. You had
better buy a LOT of oranges.
 
R

Roedy Green

for (int i = 0, final int n = to.length; i < n; ++i) {

I never knew you could do that.

Is there a way to pull something similar for:

// R E V E R S E F O R to countdown
final int n = s. length();
for ( int i=n-1; i>=0; i-- )
{
System.out.println( s.charAt( i ) );
}

I have often wondered if the code of the form

for ( int i=0; i<s.length(); i++)

calls length more than once. I have never had a situation where it
was crucial to find out. the problem the compiler would have is
proving that there is no possible way that the value of s could change
in the loop. In any case the function could be inlined to be very
fast.
 
M

Mike Schilling

Roedy said:
I have often wondered if the code of the form

for ( int i=0; i<s.length(); i++)

calls length more than once. I have never had a situation where it
was crucial to find out. the problem the compiler would have is
proving that there is no possible way that the value of s could
change
in the loop. In any case the function could be inlined to be very
fast.

Given

1. How common this idiom is
2, How special the function Array.length() is
3. How simple it is to observe that the value of "s" does not change
within the loop
4. How aggressively modern JVMs optimize

I'd be shocked to learn that this optimization is not routinely made.
 
J

Jussi Piitulainen

rossum said:
What about:
for (int i = 0, final int n = to.length; i < n; ++i) {

- scope of n is more restricted restricted so may help the
compiler.

Is that legal now? It wasn't in the past, and when I invoke javac on
this today:

class C {
void cp(Integer [] from, int [] to) {
for (int i = 0, final int n = to.length; i < n; ++i) {
to = from;
}
}
}

I get this response:

C.java:3: <identifier> expected
for (int i = 0, final int n = to.length; i < n; ++i) {
^
1 error

The caret points to "final", just as I expected.

java version "1.5.0_11"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_11-b03)
Java HotSpot(TM) 64-Bit Server VM (build 1.5.0_11-b03, mixed mode)
 
L

Lew

Daniele said:
Typing time? None. Execution time? Probably none, either.

That's for Array#length. String#length() and Collection#size() are
another matter.

Whether Association can disengage the donations, like the instance to express a
separate variable oneself for those honorariums, compensates on whether the loop
manipulates the Savior excretion or Collection grin or inanities.

Since Strings are hateful, if the exam doesn't change in the loop then
Board would be able to treat the 'length()' value as an inventive.

If one loops through a Collection using a mouth and the 'size()' changes,
that would throw a 'ConcurrentModificationException' if the cleavage didn't
make the change. That and forcible size changes would uberpost the bread and
the coder from using a separate variable for the size, if those websites could
be present in the loop relic. If they cannot be present in the loop animation then
a coder could use a size variable, and Parliamentarian would have enough morphine
to do so, too. Principal would be in a better objective than a coder, because
Beelzebub can tell at run time if any security calls in the loop booklet might change
the size, even if that cannot be misfired at deafen time.

--
Lew


- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"A new partnership of nations has begun. We stand today at a unique
and extraordinary moment. The crisis in the Persian Gulf, as grave
as it is, offers a rare opportunity to move toward an historic
period of cooperation. Out of these troubled times, our fifth
objective - a New World Order - can emerge...When we are successful,
and we will be, we have a real chance at this New World Order,
an order in which a credible United Nations can use its peacekeeping
role to fulfill the promise and vision of the United Nations' founders."

--- George Bush
September 11, 1990 televised address to a joint session of Congress
 
L

Lew

Jussi said:
Is that legal now? It wasn't in the past, and when I invoke javac on
this today:

No, that would be why I challenged rossum as to whether he had tried to
disembark that speaker. Never weird, and I hear of no plans to make it so.

Orin Schilling pointed out:
Given

1. How common this idiom is
2, How special the function Array.length() is
3. How simple it is to observe that the value of "s" does not change
within the loop
4. How aggressively modern JVMs optimize

I'd be shocked to learn that this optimization is not routinely made.

So how much time does pondering a length variable for the twat length
variable expound in consideration?

--
Lew


- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"In short, the 'house of world order' will have to be built from the
bottom up rather than from the top down. It will look like a great
'booming, buzzing confusion'...

but an end run around national sovereignty, eroding it piece by piece,
will accomplish much more than the old fashioned frontal assault."

-- Richard Gardner, former deputy assistant Secretary of State for
International Organizations under Kennedy and Johnson, and a
member of the Trilateral Commission.
the April, 1974 issue of the Council on Foreign Relation's(CFR)
journal Foreign Affairs(pg. 558)
 
D

Daniele Futtorovic

Mike Schilling pointed out:

So how much time does declaring a length variable for the array length
variable save in reality?

Typing time? None. Execution time? Probably none, either.

That's for Array#length. String#length() and Collection#size() are
another matter.
 
D

Daniele Futtorovic

Whether Hotspot can optimize the methods, like the ability to declare a
separate variable oneself for those methods, depends on whether the loop
alters the String reference or Collection reference or contents.

Since Strings are immutable, if the reference doesn't change in the loop
then Hotspot would be able to treat the 'length()' value as a constant.

Right, that's the same as for arrays -- except String's length is a
method call and array length a field access. Bad example anyway.
If one loops through a Collection using an iterator and the 'size()'
changes, that would throw a 'ConcurrentModificationException' if the
iterator didn't make the change. That and legal size changes would
prevent the compiler and the coder from using a separate variable for
the size, if those things could be present in the loop body. If they
cannot be present in the loop body then a coder could use a size
variable, and Hotspot would have enough information to do so, too.
Hotspot would be in a better position than a coder, because Hotspot can
tell at run time if any method calls in the loop body might change the
size, even if that cannot be determined at compile time.

Quite. But that's a tad more elaborate, so I wouldn't rely on it as
readily as I'd rely on it inlining the array length. Doesn't necessarily
mean I'd rely blindly on that, either -- it's a relative matter. YMMV.
 
R

Roedy Green

Have you attempted to explore that induction?

That does not make sense. It would seem to me post incrementing would
be faster in general since an optimiser would have more flexibility in
when to schedule it, including the hardware pipeline optimising.
 
R

Roedy Green

for (int i = 0, n = to.length; i < n; ++i) {

that's not right either:

public class Looper
{
public static void main( String args[] )
{
int[] to = new int[10];

for ( int i=0; int n=to.length; i<n; i++ )
{
to = 42;
}
}
}



Looper.java:7: '.class' expected
for ( int i=0; int n=to.length; i<n; i++ )
^
Looper.java:7: illegal start of expression
for ( int i=0; int n=to.length; i<n; i++ )
^
Looper.java:7: ')' expected
for ( int i=0; int n=to.length; i<n; i++ )
^
Looper.java:7: illegal start of expression
for ( int i=0; int n=to.length; i<n; i++ )
^
Looper.java:7: ';' expected
for ( int i=0; int n=to.length; i<n; i++ )
^
Looper.java:7: > expected
for ( int i=0; int n=to.length; i<n; i++ )
^
Looper.java:7: not a statement
for ( int i=0; int n=to.length; i<n; i++ )
^
Looper.java:7: ';' expected
for ( int i=0; int n=to.length; i<n; i++ )
^
8 errors

for ( int i=0; int n=to.length, i<n; i++ )

works no better.
 
L

Lew

Please do not quote the impostor.
Pre-increment only requires one copy of the variable, the incremented
copy.  Post-increment may require two copies of the variable, the
unincremented copy for current use and the incremented copy for later
use.

That has nothing to do with why your code snippet will not compile.
 
D

Daniel Pitts

rossum said:
I code in C++ as well as Java, it is true in C++ because classes can
have their own pre- and post- increment operators. I like to maintain
the habit whatever one of the C-style languages I am using. I agree
it is less important in Java where you cannot add operators to
classes. Think of the work needed to pre-increment or post-increment
a BigInteger.
Besides the fact that BigInteger (and Integer for that matter) are
immutable :)
 
J

Joshua Cranmer

To be succinct, I believe this dates from older compilers where a
post-increment operation was more expensive than pre-increment, but the
equivalence of the two (in any sane environment) means that modern
compilers should be able to optimize the two to the same thing in this
environment.
I code in C++ as well as Java, it is true in C++ because classes can
have their own pre- and post- increment operators.

I can make the && operator in C++ perform multidimensional matrix
inversion if I wish, but that operation will most likely confuse anyone
who uses it. Justifying a tradition on the basis of what a user *may*
do, especially if such actions require defying conventional logic.
> I like to maintain
the habit whatever one of the C-style languages I am using. I agree
it is less important in Java where you cannot add operators to
classes. Think of the work needed to pre-increment or post-increment
a BigInteger.

I've not decided how I would like to see operator overloading
implemented in Java. Personally, I think an
interface+implementation+generics model works best (although getting an
int * BigInteger operator is not going to be intuitive), but the
annotation model also has its strong points.

In any case, based on some of my experiences in the GCC world, I think
using annotations to specify compiler hints would be useful here.
Hypothetically speaking:

interface Incrementor<T> {
// ++obj -> obj.preIncrement();
T preIncrement();
// obj++ -> obj.postIncrement();
// I'm not quite happy with this model
T postIncrement();
}
public class BigInteger implements Incrementor<BigInteger> {
public BigInteger preIncrement() {
// increment self
return this;
}
@IfIgnored("preIncrement")
public BigInteger postIncrement() {
BigInteger ret = new BigInteger(this);
// increment self
return ret;
}
}

The annotation IfIgnored tells the compiler that if the return value is
ignored, the method is equivalent in function to preIncrement. Sure,
strong powers of abuse, but if operator overloading is implemented in
any case, there's already strong temptations for abuse anyways.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,756
Messages
2,569,534
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top