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

Discussion in 'Java' started by Royan, Aug 12, 2008.

  1. Royan

    Royan Guest

    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?
     
    Royan, Aug 12, 2008
    #1
    1. Advertising

  2. Royan

    Alan Morgan Guest

    In article <>,
    Royan <> wrote:
    >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
    --
    Defendit numerus
     
    Alan Morgan, Aug 12, 2008
    #2
    1. Advertising

  3. Royan

    Roedy Green Guest

    Re: How to instantaneously convert array of Integers into an array on int's?

    On Tue, 12 Aug 2008 14:15:32 -0700 (PDT), Royan <>
    wrote, quoted or indirectly quoted someone who said :

    >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.
    --

    Roedy Green Canadian Mind Products
    The Java Glossary
    http://mindprod.com
     
    Roedy Green, Aug 12, 2008
    #3
  4. Re: How to instantaneously convert array of Integers into an array on int's?

    Alan Morgan wrote:
    > 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".
     
    Mike Schilling, Aug 13, 2008
    #4
  5. Royan

    Lew Guest

    Re: How to instantaneously convert array of Integers into an arrayon int's?

    rossum wrote:
    > 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.)
     
    Lew, Aug 13, 2008
    #5
  6. Royan

    Roedy Green Guest

    Re: How to instantaneously convert array of Integers into an array on int's?

    On Tue, 12 Aug 2008 14:57:12 -0700 (PDT),
    (Alan Morgan) wrote, quoted or indirectly quoted someone who said :

    >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.
    --

    Roedy Green Canadian Mind Products
    The Java Glossary
    http://mindprod.com
     
    Roedy Green, Aug 13, 2008
    #6
  7. Royan

    Roedy Green Guest

    Re: How to instantaneously convert array of Integers into an array on int's?

    On Wed, 13 Aug 2008 01:01:48 +0100, rossum <>
    wrote, quoted or indirectly quoted someone who said :

    >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.

    --

    Roedy Green Canadian Mind Products
    The Java Glossary
    http://mindprod.com
     
    Roedy Green, Aug 13, 2008
    #7
  8. Re: How to instantaneously convert array of Integers into an array on int's?

    Roedy Green wrote:
    >
    > 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.
     
    Mike Schilling, Aug 13, 2008
    #8
  9. Re: How to instantaneously convert array of Integers into an array on int's?

    rossum writes:

    > 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)
     
    Jussi Piitulainen, Aug 13, 2008
    #9
  10. Royan

    Lew Guest

    Re: How to instantaneously convert array of Integers into an arrayon int's?

    Lew allegedly wrote:
    >> So how much time does declaring a length variable for the array length
    >> variable save in reality?


    Daniele Futtorovic wrote:
    > 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
     
    Lew, Aug 13, 2008
    #10
  11. Royan

    Lew Guest

    Re: How to instantaneously convert array of Integers into an arrayon int's?

    Jussi Piitulainen wrote:
    > rossum writes:
    >
    >> 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:


    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)
     
    Lew, Aug 13, 2008
    #11
  12. Re: How to instantaneously convert array of Integers into an arrayon int's?

    On 13/08/2008 14:56, Lew allegedly wrote:
    > Mike 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 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.



    --
    DF.
     
    Daniele Futtorovic, Aug 13, 2008
    #12
  13. Re: How to instantaneously convert array of Integers into an arrayon int's?

    On 13/08/2008 15:31, Lew allegedly wrote:
    > Lew allegedly wrote:
    >>> So how much time does declaring a length variable for the array
    >>> length variable save in reality?

    >
    > Daniele Futtorovic wrote:
    >> Typing time? None. Execution time? Probably none, either.
    >>
    >> That's for Array#length. String#length() and Collection#size() are
    >> another matter.

    >
    > 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.

    --
    DF.
     
    Daniele Futtorovic, Aug 13, 2008
    #13
  14. Royan

    Roedy Green Guest

    Re: How to instantaneously convert array of Integers into an array on int's?

    On Wed, 13 Aug 2008 01:20:38 GMT, Lew
    <> wrote, quoted or
    indirectly quoted someone who said :

    >> - 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?


    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.
    --

    Roedy Green Canadian Mind Products
    The Java Glossary
    http://mindprod.com
     
    Roedy Green, Aug 13, 2008
    #14
  15. Royan

    Roedy Green Guest

    Re: How to instantaneously convert array of Integers into an array on int's?

    On Wed, 13 Aug 2008 14:45:21 +0100, rossum <>
    wrote, quoted or indirectly quoted someone who said :

    > 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.
    --

    Roedy Green Canadian Mind Products
    The Java Glossary
    http://mindprod.com
     
    Roedy Green, Aug 13, 2008
    #15
  16. Royan

    Lew Guest

    rossum wrote:
    > >> 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.



    NewsMaestro wrote:
    > >Have you attempted to explore that induction?


    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.

    --
    Lew
     
    Lew, Aug 13, 2008
    #16
  17. Royan

    Lew Guest

    On Aug 13, 11:33 am, Roedy Green <>
    wrote:
    > Not-Lew wrote:
    > >Have you attempted to explore that induction?


    Please do not quote the impostor.

    --
    Lew
     
    Lew, Aug 13, 2008
    #17
  18. Royan

    Lew Guest

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


    On Aug 13, 11:48 am, Roedy Green <>
    wrote:
    > that's not right either:


    Yes it is. Your examples were different.

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


    Illegal syntax.

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


    Illegal syntax.

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


    Legal syntax.

    --
    Lew
     
    Lew, Aug 13, 2008
    #18
  19. Royan

    Daniel Pitts Guest

    Re: Dissasembly pre and post increments (was Re: How to instantaneouslyconvert array of Integers into an array on int's?)

    rossum wrote:
    > On Wed, 13 Aug 2008 19:43:57 +0200, Andrea Francia
    > <_FROM_HERE_ohohohioquestoèdatogliereohohoho_TO_HERE.it>
    > wrote:
    >
    >> I don't know why it's good habit using the pre-increment, but this is
    >> not the first time I have heard this thing.

    > 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 :)
    > rossum
    >



    --
    Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>
     
    Daniel Pitts, Aug 14, 2008
    #19
  20. Re: Dissasembly pre and post increments (was Re: How to instantaneouslyconvert array of Integers into an array on int's?)

    rossum wrote:
    > On Wed, 13 Aug 2008 19:43:57 +0200, Andrea Francia
    > <_FROM_HERE_ohohohioquestoèdatogliereohohoho_TO_HERE.it>
    > wrote:
    >
    >> I don't know why it's good habit using the pre-increment, but this is
    >> not the first time I have heard this thing.


    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.

    --
    Beware of bugs in the above code; I have only proved it correct, not
    tried it. -- Donald E. Knuth
     
    Joshua Cranmer, Aug 14, 2008
    #20
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. CK
    Replies:
    6
    Views:
    1,516
    Steve C. Orr [MVP, MCSD]
    Feb 23, 2005
  2. Markus Zeindl

    How do I convert characters into integers?

    Markus Zeindl, Dec 14, 2004, in forum: Python
    Replies:
    8
    Views:
    422
  3. Tomás Ó hÉilidhe

    Convert native character string to ASCII array of integers

    Tomás Ó hÉilidhe, Mar 28, 2008, in forum: C Programming
    Replies:
    56
    Views:
    2,717
    CBFalconer
    Mar 31, 2008
  4. krishna
    Replies:
    2
    Views:
    447
    samwyse
    Jun 25, 2009
  5. seektime
    Replies:
    23
    Views:
    412
    Prasad, Ramit
    Oct 25, 2012
Loading...

Share This Page