Programming Java 2 Micro Edition for Symbian OS 2004 (779882), страница 61
Текст из файла (страница 61)
The approach taken is to encourage you to think aboutthe issues involved and to make rational decisions, rather than attemptingto provide hard and fast rules for optimization.We start with a number of general issues including current technology,benchmarking and principles of optimization.The next few sections discuss several specific areas for optimization:object creation, method and variable modifiers, the use of Strings andusing containers sensibly. These ideas are brought together in an examplein Section 7.10.We then look at some more advanced techniques, such as blockingtechniques to avoid polling and issues with graphics.Section 7.14 provides a case study which explores optimization issuesin depth.
The use of profiling tools is examined in the context of thecase study.Subsequent sections discuss design patterns relevant to optimization,memory issues on constrained devices and the need to cope with out-ofmemory situations, and JIT and adaptive compilation technologies.Useful general references on Java optimization are:• Practical Java Programming Language Guide by Haggar• Java 2 Performance and Idiom Guide by Larman and Guthrie• Java Performance Tuning by Shirazi.Programming Java 2 Micro Edition on Symbian OS: A developer’s guide to MIDP 2.0.
Martin de Jode 2004 Symbian Ltd ISBN: 0-470-09223-8336WRITING OPTIMIZED CODE7.2 What Are We Starting With?Mobile phones are, by their nature, memory-constrained. In comparisonto a desktop computer we have a small screen, a keypad or pointer forinput rather than a keyboard or mouse, restricted memory, restricted network and IO performance, and restricted processing power. Of particularconcern in this chapter are memory, IO and processor performance.Mobile phones running Symbian OS typically have between 8 and16 MB of RAM.
The desktop computer on which I am writing this has512 MB of RAM!Serial IO on a Symbian OS device is reasonable: both the IR and serialports operate at 115.2 Kbps. Bluetooth rates are slightly faster, typicallyseveral hundred Kbps, but this is still far short of my office network, whichruns at 100 Mbps, and my wireless LAN, which operates at 10 Mbps.Currently, mobile networking is more constrained. GSM provides9.6 Kbps and GPRS 2.5G technology increases this to over 100 Kbps.3G UMTS will provide a maximum of 2 Mbps, though typical data rateswill be much lower than this. 3.5G UMTS High Speed Downlink PacketAccess (HSDPA) could increase the maximum rate to 10 Mbps.7.3 BenchmarkingBenchmarking wireless devices remains problematic. The EmbeddedMicroprocessor Benchmark Consortium (EEMBC, see www.eembc.hotdesk.com) has created a suite of embedded Java benchmarks calledGrinderBench, and is working on UI and graphics benchmarks.
GrinderBench benefits from using engines from real-world applications, such ascryptography, chess and XML parsing.The table below gives overall results for AMark and CLDCMark tests.AMark is a basic graphics benchmark which can be downloaded fromhttp://amark.nondove.it. AMark Version 1.3 is run at a standard sizeframe, which overcomes the effect of screen size variability. CLDCMarkis a benchmark used internally within Symbian; it is purely embedded,with no graphics tests.
For both tests, the bigger the number, the faster thedevice is running. As well as Symbian OS devices, we have included theMotorola A760 (a Linux-based phone with a 200 MHz XScale processor)and Sun’s Wireless Toolkit running on a 600 MHz laptop.SunMotorola Nokia Nokia Nokia SonySonyWireless A760 9210i 7650 6600 Ericsson EricssonToolkitP800P9002.1AMark 1.3CLDCMark35.7924847268.03 17.13 20.48396 674 332019.79423842.635013GENERAL GUIDELINES FOR OPTIMIZATION337The table shows how rapidly Java performance has improved, throughfaster clock rates and improved VM technology. Since the Nokia 9210,the embedded tests have improved by well over a factor of 10, and thegraphics tests by a factor of five.
The Nokia 6600 onwards use Sun’sCLDC HI VM. The Wireless Toolkit results are intriguing: a very goodgraphics performance but a very poor embedded performance.Benchmarks should always be viewed with caution: the only real testis running representative applications on representative hardware.7.4 General Guidelines for OptimizationThis section outlines some general principles for optimizing code.
Thesedo not attempt to say anything new; however, restating the obvious is notalways a bad thing.• get the design rightThe biggest gains generally come from getting the overall architectureand design right: how operations should be split between server andclient, what technologies to use (e.g. messaging, RMI, object databaseor relational database), what hardware to use, even what languagesare used.It is important to design to interfaces, not implementations.
Thismakes it easier to slot in a different or improved algorithm: forexample, depending on your data size and how it might already besorted, there are times when a pigeon sorting algorithm will be thebest choice, and times when a bubble sort will be appropriate.• optimize late: optimizing too early in the process means that you willproduce intricate code that gets in the way of good design• optimize only where necessary: find out where the bottlenecks areand concentrate on sorting them out; this requires access to suitableprofiling and heap analysis tools• do not over-optimize.The more you optimize your code, the more highly tuned it becomesto the particular environment.
If the environment changes or you wantto use the code in a different application, it may run more slowly.Compiler technology in particular can have a profound effect on thebenefits or otherwise of a particular optimization.Optimization can often conflict with other goals for the code:• clarity and maintainability: improving performance at the code levelgenerally (though not always) means writing more, and often quiteobscure, code (we shall see an example of this in the case study inSection 7.14)338WRITING OPTIMIZED CODE• reliability: the corollary of the previous point is that you run the riskof introducing bugs when you optimize• fast startup time and fast executionWe can frequently improve startup time by deferring a task until itis required during execution. This is worthwhile if the task may notalways be required, and even then may still be worthwhile, especiallyif the task can be carried out by a background thread.• reducing memory usage: many of the optimizations require extracode; caching is a vital tool in improving performance, but requiresextra memory.Finally, the behavior of an optimization will vary with the platform.
As aJava developer for Symbian OS phones you are likely to be working withthree platforms: Java under Windows, the Emulator and a target device.The first two platforms may give a rough idea of the benefits or otherwiseof an optimization; however, they cannot be used for a reliable analysis.The performance of the Emulator in particular is very different to that oftarget hardware, for reasons we shall discuss.7.5 Feedback and ResponsivenessPerformance is in the eye of the beholder, so as well as being fast asmeasured by a stopwatch, our application also needs to be responsive tothe user and to provide feedback.
The user should never be confrontedwith an unresponsive screen that shows no indication that somethingis happening. Large applications, in particular, can take a long time toinitialize. Rather than leave the user with a blank screen, pop up asplash screen.Unlike on desktop computers, there is generally no wait icon onmobile phones. Therefore it is necessary to have a status area, animatedicon or some other way of conveying progress to the user.Threads are an expensive resource and should therefore be usedjudiciously; this is why native Symbian OS applications tend to be singlethreaded and to rely on cooperative multitasking. You might, however,want to consider loading or saving data in a separate thread, which allowsthe user to carry on with other work.
Windows applications often lockthe user out while a file is being saved; this is frustrating and unnecessary.While saving a file, the user should still be able to read it or edit anotherfile of the same type.7.6 Object CreationObject creation is an expensive process, so it is worth examiningyour design to ensure you are not creating large numbers of objects,OBJECT CREATIONFigure 7.1339DiceBox on P900.particularly short-lived objects, and to consider reusing objects. TheAWT, for instance, is notorious for creating lots of short-lived objects; onthe other hand, the MIDP designers took great care to minimize objectcreation, so very few event objects, for instance, are created.Reusing objects means we do not waste time recreating objectsand there is less work for the garbage collector when they are nolonger needed.Figure 7.1 shows the DiceBox MIDlet, which rolls a number of dice ina similar way to a fruit machine rolling fruit.The following is an extract from the DiceCanvas constructor usedto display the dice.
We create a List to change the number of dice inthe constructor rather than recreate it every time it is displayed. We alsocreate a pool of dice, six in this case, rather than create new dice everytime we change their number.class DiceCanvas extends Canvas implements CommandListener, Runnable{...List diceNumberList = new List("Select number of dice",List.IMPLICIT, new String[] {"1","2","3","4","5","6"}, null);int numberOfDice = 2;Dice[] die = new Dice[6];public DiceCanvas(DiceBox midlet){for(int i = die.length; --i >=0; )die[i] = new Dice();...340WRITING OPTIMIZED CODEA valid alternative would be to create just the first four dice for ourdice pool and then create additional dice only when we increase thenumber of dice.It should be emphasized that we have used the DiceBox MIDlet only toillustrate a point. In a program as small as this, such decisions make littlepractical difference and worrying about them too much should definitelybe regarded as over-optimization.