Will java programs become slower with generics?

This is not a question, more lika general discussion. I'd like to know what you think.
I fear that the average java developer will become accustom to the new features of java and write inefficient code. I have included a sample program that shows new code vs. old code. Altough the new code is esier to read, it's also alot slower.
For instance the foreach instruction is using an iterator which is created and then iterated. When the loop exits the Iterator is garanage collected. Better performance would be achieved if there was a "Getable" interface of some sort was implemented and that the foreach simply asked the collections class for the next object in line. Perhapps if the ArrayList cached it's Iterator objects, somehow. (I'm not suggesting any of the solutions above. I'm just trying to make a point.)
Also regarding generics and enumerations it's easy to see how they will slow down the application. It gets even scarier when you consider that important foundation classes are updated with these new features. A small change in some AWT class may have unforeseen repercussions throughout all gui applications.
Gafter, if you read this, is there any tests made to see if this is true. Is performance affected by the new features? Will old style code be replace by new style code in the foundation classes (awt/swing/.../... etc.).
ArrayList<String> ss = new ArrayList<String>();
for (int i = 0; i < 100; i++) ss.add("hello");
// "new" java ... completes in 6.43 seconds
long t1 = System.nanoTime();
for (int i = 0; i < 1000000; i++)
     for (String s : ss)
System.out.println(System.nanoTime()-t1);
// "old" java ... completes in 2.58 seconds
long t2 = System.nanoTime();
for (int i = 0; i < 1000000; i++)
     for (int j = 0, size = ss.size(); j < size; j++)
          String s = ss.get(j);
System.out.println(System.nanoTime()-t2);

Adapting Neal's example for JDK 1.4:
    private static final String[] strArray = new String[0];   
    private static void withToArray() {
        List ss = new ArrayList();
        for (int i = 0; i < 100; i++) ss.add("hello");
        long t1 = System.currentTimeMillis();
        for (int i = 0; i < 1000000; i++)
            String[] ssArray =  (String[]) ss.toArray(strArray);
            for (int j=0;  j < ssArray.length; j++) {
                String s = ssArray[j];               
        System.out.println(System.currentTimeMillis()-t1);
    private static final String[] strArray100 = new String[100];   
    private static void withToArrayAndCheatingOnLength() {
        List ss = new ArrayList();
        for (int i = 0; i < 100; i++) ss.add("hello");
        long t1 = System.currentTimeMillis();
        for (int i = 0; i < 1000000; i++)
            String[] ssArray =  (String[]) ss.toArray(strArray100);
            for (int j=0;  j < ssArray.length; j++) {
                String s = ssArray[j];               
        System.out.println(System.currentTimeMillis()-t1);
    private static void withToArrayAndCheatingOnLengthLocalVar() {
        List ss = new ArrayList();
        for (int i = 0; i < 100; i++) ss.add("hello");
        final String[] localStrArray100 = new String[100];           
        long t1 = System.currentTimeMillis();
        for (int i = 0; i < 1000000; i++)
            String[] ssArray =  (String[]) ss.toArray(localStrArray100);
            for (int j=0;  j < ssArray.length; j++) {
                String s = ssArray[j];               
        System.out.println(System.currentTimeMillis()-t1);
    } Allocating the string[] every time: 5812
Allocating the correctly sized string[] once, as a private final static: 2953
Allocating the correctly sized string[] once, as a final local var: 3141
Interesting that the private final static is 90ms faster than the local variable, fairly consistently.
What's interesting about that though, is that we're not iterating strArray100, we're iterating over ssArray, so its not clear why it should make a difference. If I modify things a little more:
    private static void withToArrayAndLoopOptimization() {
        List ss = new ArrayList();
        for (int i = 0; i < 100; i++) ss.add("hello");
        long t1 = System.currentTimeMillis();
        for (int i = 0; i < 1000000; i++)
            String[] ssArray =  (String[]) ss.toArray(strArray100);
            final int length = ssArray.length;              
            for (int j=0;  j < length; j++) {
                String s = ssArray[j];               
        System.out.println(System.currentTimeMillis()-t1);
    private static void withToArrayAndLoopOptimizationLocalVar() {
        List ss = new ArrayList();
        for (int i = 0; i < 100; i++) ss.add("hello");
        final String[] localStrArray100 = new String[100];           
        long t1 = System.currentTimeMillis();
        for (int i = 0; i < 1000000; i++)
            String[] ssArray =  (String[]) ss.toArray(localStrArray100);
            final int length = ssArray.length;  
            for (int j=0;  j < length; j++) {
                String s = ssArray[j];               
        System.out.println(System.currentTimeMillis()-t1);
    }  With private static final and loop optimization: 2937
With local variable and loop optimization: 2922
Now the different has disappeared: in fact, the numbers are exactly the same on many runs. You have to make 'length' final to get the best speed.
I guess I'm disappointed that in 2004, Java 1.4 javac & Hotspot combined still cannot spot the simplest loop optimization in the book.... always assuming that's actually causing the preformance difference. My gut is telling me its something else causing the difference because all of the inner loops are iterating over ssArray, not strArray100 (wherever that happends to be declared).
Someone care to run Neal's example on 1.5 and see if they've managed to optimize further under the covers?

Similar Messages

  • HT4623 Will my ipad become slow if i update my i pad software

    Will my ipad become slow if i update my i pad software

    I would think twice about updating with an iPhone 4S. Look around the forums to see many people are sorry they did. Not because iOS 7 is bad, but because the 4S is much too slow to run it well.
    And no, you will not lose your contacts but backup first.

  • Java 2D very slow with Windows XP

    Hi all!
    I'm writing an isometric game engine using Java 2D API, in full-screen exclusive mode and using all the advantages of the new VolatileImage class. The engine is almost finished, I'm testing it putting some animated players on screen and showing the frame rate of the engine. Everything went right, frame rate was very high in Linux and Windows 98/Me. But when I try to run the engine on Windows XP I can only get 5 or 6 fps!!!! And I don't know why!! It seems that XP makes Java run very slow... at least when using Java2D...
    Please, anyone knows why the performance is reduced??? Is there a new JRE release for Windows XP?? I'm using JDK 1.4.1.
    Thanks for your help.

    If you're using the Fullscreen API, then you're using BufferStrategy, thus you shouldn't use VolatileImages, it does this for you in the background. You shouldn't create any buffers, simply use the one provided. I'm assuming your problem probably lies in transparency. I've made an isometric engine using the fullscreen API that has run with complete 60fps page flipping. I would assume your bottle-neck lies in:
    Transparencys (These are very slow, there is a way to make a bitmask, much like you'd do in DirectX)
    Dynamic Memory allocation/Alpha rendering in your animation loop. (You need to allocate ALL of the colors you're going to use, and avoid using an alpha component if you want to avoid the VM getting bogged down by the garbage collector because you're allocating 30 Color objects a second).
    I made a Color object that was some what hacked together that has methods to allow you to access it's values for doing this kind of thing, allocating your scheme before hand is an easier approach.
    The method that performs the page flipping is a BLOCKING method, so you should orient your drawing before it, and not assume it's simply placing a request, like repaint does.
    -Jason Thomas.

  • Why is my mail program so slow with Yosemite

    I am running 10.10.1 on my G5 (2010). Mail program is not running as before I upgraded. Everything in my mail is slow: typing, incoming, outgoing... Any ideas?

    These instructions must be carried out as an administrator. If you have only one user account, you are the administrator.
    Launch the Console application in any of the following ways:
    ☞ Enter the first few letters of its name into a Spotlight search. Select it in the results (it should be at the top.)
    ☞ In the Finder, select Go ▹ Utilities from the menu bar, or press the key combination shift-command-U. The application is in the folder that opens.
    ☞ Open LaunchPad and start typing the name.
    Step 1
    For this step, the title of the Console window should be All Messages. If it isn't, select
              SYSTEM LOG QUERIES ▹ All Messages
    from the log list on the left. If you don't see that list, select
              View ▹ Show Log List
    from the menu bar at the top of the screen.
    In the top right corner of the Console window, there's a search box labeled Filter. Initially the words "String Matching" are shown in that box. Enter "BOOT_TIME" (without the quotes.)
    Each message in the log begins with the date and time when it was entered. Select the BOOT_TIME log message that corresponds to the last failed boot. Now clear the search box to reveal all messages. Select the ones logged before the boot, during the time something abnormal was happening. Copy them to the Clipboard by pressing the key combination command-C. Paste into a reply to this message by pressing command-V.
    For example, if the system was unresponsive or was failing to shut down for three minutes before you forced a restart, post the messages timestamped within three minutes before the boot time, not after. Please include the BOOT_TIME message at the end of the log extract—not at the beginning.
    If there are long runs of repeated messages, please post only one example of each. Don’t post many repetitions of the same message.
    When posting a log extract, be selective. A few dozen lines are almost always more than enough.
    Some private information, such as your name, may appear in the log. Anonymize before posting.
    Please don't indiscriminately dump thousands of lines from the log into this discussion.
    Please don't post screenshots of log messages—post the text.
    Step 2
    In the Console window, select
              DIAGNOSTIC AND USAGE INFORMATION ▹ System Diagnostic Reports
    (not Diagnostic and Usage Messages) from the log list on the left. If you don't see that list, select
              View ▹ Show Log List
    from the menu bar.
    There is a disclosure triangle to the left of the list item. If the triangle is pointing to the right, click it so that it points down. You'll see a list of reports. A crash report has a name that begins with the name of the crashed process and ends in ".crash". A panic report has a name that begins with "Kernel" and ends in ".panic". A shutdown stall report has a name that ends in ".shutdownstall". Select the most recent of each, if any. The contents of the report will appear on the right. Use copy and paste to post the entire contents—the text, not a screenshot. It's possible that none of these reports exists.
    I know the report is long, maybe several hundred lines. Please post all of it anyway.
    If you don't see any reports listed, but you know there was a crash or panic, you may have chosen Diagnostic and Usage Messages from the log list. Choose DIAGNOSTIC AND USAGE INFORMATION instead.
    In the interest of privacy, I suggest that, before posting, you edit out the “Anonymous UUID,” a long string of letters, numbers, and dashes in the header of the report, if it’s present (it may not be.)
    Please don’t post other kinds of diagnostic report—they're very long and rarely helpful.

  • Can you do the Java equivalent of this with Generics?

    hi,
    http://www.informit.com/content/index.asp?product_id=%7B4BCD9193-97E4-4004-AF84-D7346E261C69%7D
    thanks,
    asjf

    Think of specialization as "compile-time" polymorphism. It allows you to create different implementations of methods/classes for different types, selected at compile-time. For example, I use template specialization extensively in Jace to unify entire sets of type-disparate JNI functions.
    Specialization is a very powerful technique and is also used extensively in template meta-programming (which brings us back to the OP). Even were the current form of Java generics to somehow magically support some form of specialization, you still wouldn't be able to perform meta-programming as Java generics don't work with constants.
    Any surface similarities between Java generics and C++ templates expire at trivial inspection, which means that it's a fairly futile exercise to try to compare the two.
    God bless,
    -Toby Reyelts
    Check out the free, open-source, JNI toolkit - Jace, http://jace.reyelts.com/jace

  • LV7.1 compiled program runs slow with disc. type defs checked

    I am working on a VI (with about a hundred sub-VIs) written by someone else (who is no longer available to answer questions about it).  I've done only a few minor updates, but when I re-compiled it, the resulting EXE ran several times slower than the original.  As an experiment, I unticked the "Disconnect type definitions and remove polymorphic VI instances" checkbox in the compile options, and this resulted in a much faster EXE.  I could post the VIs, but I would bet that most folks here don't have the time to look through it (programming style is very "spaghetti code"-ish).  For what it is worth, the main VI consists of a couple of one-time code blocks and two large While loops (one for number crunching and the other for GPIB instrument control).  Also, the various VIs use a LOT of locals, arrays, text files, property nodes and invoke nodes.
    Any ideas on what to look for?  The program runs fine in the development environment (run on the same PC as the EXE).
    Regards,
    Michael Tracy
    Synergy Microwave

    The only thing that option should do for you is to replace the type defs with equivelent non-typed version and toss all of the polymorphic versions that are not used.
    So if I focus on the replacing type defs part...
    That process may have resulted in the defaults of your controls be lost so if any of your typedef'd controls have a large or bogus default value, then not removing them MAY preserve the default data. If the replaced version have empty default data then they may be able to run more efficiently.
    Yes all of that is wild specualtion!
    So you could check your code for non-empty default data...
    Just trying to help,
    Ben
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction

  • When will creative labs become compatible with AAC fil

    I've been using itunes to upload music and I wanted to know when creativelabs will be compatible with the itune friendly AAC files.

    Time to rip this post apart.
    <<I'll hand it to you for persistence, although I don't know why you CONTINUALLY try to disrupt a tech forum for Creative with pro-Apple BS.>>
    Pro-Apple BS? How was pointing out that AAC is an open format pro-Apple? It's not. Don't make up things. All I did was point out that AAC is open and that it can be played on any OS, or any MPEG-4 compatible software or hardware.
    <<AAC is a proprietary format. It is, as you should know, based on the audio specification for MPG4, which came out over 6 years ago. Dolby Labs controls the licensing of this format, the codec and the chips to decode and encode it. The fees are substantially higher than those for WMA, and of course, than MP3.>>
    Stop getting your information from that post on Napster that I debunked MONTHS ago. I proved that wrong and you know very well that it's wrong. Anyway, Dolby does control the licensing for MPEG-4 AAC, yes. However, licensing fees are not anything like you or that Napster post said. I provided information back then, so you can go back and look for yourself, if you're still choosing to throw your money away on Napster. If licensing fees are so bad, then why are there so many freeware players that play AAC files? MPEG-4 AAC files! Why? Why can I download a FREE operating system (Linux), and use completely free software to rip and play AAC files? Exactly. iTunes is freeware you know. Why can I download it for free and rip and play AAC files? Surely Apple isn't going to front the bill for millions of people to use iTunes to just rip, organize, and play their music.
    <<AAC is not the logical successor to MP3. If only WMA or AAC are considered, then WMA is the clear winner in that race. >>
    How is WMA the clear winner? Besides the fact that WMA sounds noticably inferior at any bitrate.... Even HE-AAC mops the floor with WMA9 Pro at low bitrates. Anyway, how is WMA the clear winner? AAC compatible digital audio players control *90%* of the hard dri've market, 43% of the flash market, and a combined total of over *70%* of the entire market. Let's not forget that the number one online music store, which controls over 70% of the market, uses AAC as it's format of choice, and the next biggest online store behind very distant number 2 Napster is using AAC as well. Soon Napster will be launching a "music to go" rental service that targets ALL platforms. Can you guess the file format of choice? AAC
    <<In fact, WMA9 Pro is under consideration for the next generation "CD" compression. This, along with DVD-A and SACD. Note there is nothing from Dolby under consideration at all. >>
    hahahaha says who? Actually, since MPEG-4 is part of the HD-DVD and Blu-Ray specs, AAC is already part of the deal And, right now, SACD has the same market penetration that CD at the same point in it's lifetime. So SACD is well on it's way to becoming the "next CD". As it looks right now, SACD will become the CD format of "tomorrow", while the iTunes Music Store is handling the current "CD quality" music business just fine. As it stands though, honestly, it will be a combination of two things. SACDs for audiophiles, and iTunes-like downloads for everyone else.
    Also, Dolby only handles the licensing portion of AAC. AAC was developed by a number of companies, including Sony. Sony has a stake in SACD, blu-ray, and any optical disc technology that comes out. So I can guarantee you that they will not let AAC die, even if it kills their precious atrac3/atrac3plus format.
    And another thing to consider is that the recording industry wants a standard across all platforms for digtial music downloads. And considering 70% of the market is AAC compatible, and by the end of this year, a certain online music store will have passed over $b in total revenue, you can imagine which format will win.
    <<Even assuming the original poster meant he wants to load non-DRM ("Fairplay") tracks on his Creative player, it will not likely happen so long as Apple is intent on blocking 3rd parties from using purchased iTunes songs on any other player.>>
    What does iTunes purchased songs have to do with AAC files ripped from anyother source? Exactly. Using Apple is an excuse for companies to not support AAC. It's their loss though. If Creative would support AAC, they would have opened themselves up to the market of millions of people who do use iTunes and Real Player 0+ to rip their CDs.
    <<It is unlikely Creative will spend the license money for a purpose so limited as self-ripped AAC files when there are other free alternati'ves to somebody ripping their own CD's.>>
    How are AAC files limited? AAC files can be played and ripped on any platform. If you want to talk about limited, you have to look at WMA. It only works under one OS and only certain players can play it. And what free alternati'ves are there? MP3 licensing isn't free. WMA licensing isn't free. If you're selling a player for profit, you HAVE to pay for WMA and MP3 decoding capabilities.
    <<AAC is a good-sounding compressed format, but for mass acceptance it will always remain a niche unless Apple opens things up and Dolby lightens up on their expesi've licensing.>>
    Mass acceptance? AAC has already been accepted by the masses. Over 350 million songs sold in AAC, and 70% of the digital audio player market is AAC compatible. I think players that DON'T support AAC are currently in the niche market
    <<Something good like Oog Voorbis has a better chance of becoming the successor to MP3, I think, and even that remains a niche at this point. >>
    Ogg Vorbis will never replace MP3s. First off, the sound quality isn't as good as AAC. Secondly, Ogg Vorbis requires a processor with a FPU. FPU require more battery power, so battery life is affected significantly. And most importantly, there are no CONVENIENT Ogg Vorbis encoders. Not to mention Ogg Vorbis still has a lot of bugs that need worked out. They only recently worked out a bug that was causing significant high end distortion that greatly affected the sound quality of the files. Plus Ogg Vorbis has no DRM container.
    Also, transcoding a file degrades the sound quality significantly.

  • How do you yeploy Java Program (including database) with Netbeans

    I need to deploy an application I wrote with NetBeans IDE as a jar file such that it would run on any machine other than the development machine. I used MySQL database in this application and i dont want to have to install MySQL on every machine i install it on. Also, the application makes use of bluecove's bluetooth SDK (a .jar file) How do I do this using netbeans? Anyone?

    MySQL will have to be installed where is's used. If you replace it with an embedded version of Derby that could be eliminated.
    NB tutorials cover many subjects, including desktop deployment:
    http://www.netbeans.org/kb/articles/javase-deploy.html
    Further NB questions should be posted to an NB website; these forums are for Java language questions.

  • Java program to interface with Microsoft Outlook and Exchange.

    I am in the process of writing a Java GUI application that can connect to Microsoft Exchange servers and get appointments information.
    I tried using JIntegra's Java Exchange Bridge but I keep getting a "AutomationException - class not registered" error whenever my code gets to the part where it attempts to login.
    Ive configured everything properly and have the appropriate access.
    Can anyone help me or give me some ideas of another way to implement this GUI?
    Thanks

    Ive configured everything properlyQuite likely not.
    I know almost nothing about JIntegra -- but when I look at their website, I see a "Support" page and a "Knowledge Base" page. Seems to me there is a much higher density of expertise over there than there is here.
    I know in Windows you can't use a DLL unless you've registered it, which does something to your registry. And you have to be an administrator to do that. Perhaps you have to do something like that on your machine.

  • Will java support swings along with sip protocol

    sir i want the java and sip protocol to be used aside by aside by aside

    Do you mean you want do use SIP from Java? Google for "sip java" and e.g. the first hit is about a SIP API for Java.

  • Shifting of  consumer becoming slower with time

    Oracle database 8i
    OS windows 2000 server
    I have one procedure for Shifting of consumers from one electric pole to another which incluedes updation and deletion at one go and no commit after each migration but commit at last.
    After execution of procedure it takes 10 sec to migrate one consumer but
    after a while it takes 2 to 5 minutes for each consumer.
    I guess it's a matter related to rollback segment .
    How I can maintain the consistency in performance?

    I guess it's a matter related to rollback segment .Instead of guess, I would advise you to get a 10046 trace for the given workflow and pinpoint the problem.

  • How do you start a java program with more RAM alloaction

    Hi
    can anyone please tell me how to start a java program to start with lots of RAM (RAM size is sent as a parameter), I have seen it somewhere and now I cant remember it. I have a server application to run this way.
    thanks and rgds
    sunil

    see the tooldocs of java: http://java.sun.com/j2se/1.4/docs/tooldocs/tools.html

  • Java running under linux with crontab

    I'm having a problem:
    i want to run a java program under linux with crontab.
    my classes are in a directory and aren't in a package. i run em by invoking ./start which is a small script that i wrote. The script is in the same dir as the classes and invokes java by "java Main >>logjava.txt " but this doesn't seem to work all i get is an empty logfile
    i need to run the program every day at 0800 so i inserted the following in crontab:
    0 8 * 1-5 /var/"path"/start > logjava (where path is the path to the classes dir)
    if i run the cmdline from anywhere on the prompt i get the result i want. I think it's because the cron runs it from the root dir thus making java unable to find the classes
    Any suggestions would be welcome. or can some1 tell me how to make linux executables from the java (i usually use jsmooth for the windows exe)

    You can execute several commands in the process started by cron. You separate them using semicolons.
    Have you tried a cron entry like this:
    0 8 * 1-5 cd /var/"path";pwd;echo $PATH; ./start > logjavaOr, you may need to make sure the process started by cron gets the same environment as your interactive shells do, by explicitly loading your setup or .login scripts:
    0 8 * 1-5 . $HOME/.setup;cd /var/"path";pwd;echo $PATH; ./start > logjava

  • Ore program makes my Java Program crash, which uses lots of memory (Urgent

    I use a very huge HashMap to calculate something, and the HashMap size
    may be increased dynamically.
    And I start the program with -Xms300M -Xmx300M (The OS is Win2000).
    When I start some programs which may use more memory , My program shows
    that the free memory is absolutely enough , but suddenly, The thread to
    handle the HashMap seems to be hanged, and the free memory is shown to be
    reduced continuously.
    At this time, I can't stop the program, Sometimes I can't kill it by the
    Task Management Manager.
    It seems that my java program is robbed with physical memory, and
    encounter memory problem, and can't restore from it?
    Would you please tell me how to fix this problem?
    Thank you very much!
    Sincerely,
    Fang Jing
    [email protected]

    Looks more like an endless loop to me.
    Can you post the code where the problem occurs?

  • Java program in XP - Please Help

    Hi, I am not sure if I am in the right fourm. I am not a developer, but a network engineer trying to help out my wife. My wife uses a java program to monitor the company she works for web site, which is not linked to a web browser. When she received the java program, it came with Java 1.2.2. Our PC had Windows 98 installed. I purchased a new machine, with Windows XP on it, and installed the java program and JRE on to it. The program does not work. The programmer who wrote the program was fired a few months ago, so I started looking through the internet, and the Sun fourms for a solution. First, the XP machine does not have Microsoft VM on it. Second, I upgraded the java to 1.4.1_02, following the instructions, still with no success. There was a suggestion to dual boot with Windows 98, but I really do not want to do that. What happens is - when you log in to the program, it just freezes. It does not go into the server. Any help is greatly appreciated.

    Possible reasons for the program hanging up
    1) The version of the VM on the machine is not correct.
    2) Even if the version is correct and correctly installed, can you please check whether the PATH and CLASSPATH variables are set correctly on the machine where you are running the program.
    3) I use WINXP as well with the latest version of VM downloaded from Sun and NOT Microsoft.
    Hopefully this might solve the issue.

Maybe you are looking for