Главная » Просмотр файлов » Programming Java 2 Micro Edition for Symbian OS 2004

Programming Java 2 Micro Edition for Symbian OS 2004 (779882), страница 62

Файл №779882 Programming Java 2 Micro Edition for Symbian OS 2004 (Symbian Books) 62 страницаProgramming Java 2 Micro Edition for Symbian OS 2004 (779882) страница 622018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 62)

Object creation is also less expensiveon Sun’s CLDC HI VM than on the original KVM.Consider using object pools for such things as database connectionsand server connections. For instance, a file server program waits for arequest from a client and on receipt of a request returns the appropriatefile. The program might use a class called FileRequestHandler tolisten for, and respond to, file requests from the client. It creates aFileRequestHandler for each client it is serving, presumably on theport returned by ServerSocketConnection.acceptAndOpen().Alternatively it can create a pool of FileRequestHandler instancesat startup and reinitialize an instance with the appropriate port numberas needed.The benefits of using a pool of FileRequestHandler instances willbe a faster connection time and an implicit limit on the number of clients.This means a client is either guaranteed adequate bandwidth or has towait for a free FileRequestHandler.

The downside could be a slowerstartup time.Object creation and pooling is discussed in detail in Smart objectmanagement saves the day by Sosnoski (www.javaworld.com/javaworld/jw-11-1999/jw-11-performance.html).7.7 Method Modifiers and InliningJava provides a number of modifiers to control the scope of methods and variables: private, protected, public, final, staticand volatile.Methods or variables with no modifier have package scope, are nonstatic (that is, belong to the instance of a class rather than the classitself) and are non-final (that is, can be overridden in a derived class).We tend to use the default without thinking too much about it; it is areasonably safe compromise.

However, we should not be lazy. As gooddesigners we should keep things as private as possible and expose onlywhat we absolutely have to. Invariant data (constants) should, in anycase, be marked as static and final. Such an approach reduces therisk of being stuck with an unsatisfactory public interface; we can alwaysopen up our design later, but it is very hard to go back once we makesomething public.METHOD MODIFIERS AND INLINING341Performance will also be affected by the scope of our objects andvariables. Local variables remain on the stack and so can be accesseddirectly by the VM (a stack-based interpreter).

Static and instance variablesare kept on the heap, and can therefore take much longer to access.static int sValue = 1;int iValue = 2;void lotsOfVariables(int arg1, int arg2) {int value1;int value2;value1 = arg1;value2 = arg2;iValue = sValue;}In the above code snippet, sValue is a static and iValue is aninstance variable; both are stored in the heap. value1 and value2 arelocal variables, arg1 and arg2 are method arguments, and all four arestored on the stack.The following table shows the performance difference in accessingstatic, instance, and local variables (see the Microbench MIDlet in thesource code for the book, at www.symbian.com/books).

In each case theexecuted code was of the form:value1value2value3value4====value2;value3;value4;value1;where value<n> is either a static, an instance or a local variable. Thiscode was repeated 16 times in each loop, giving 64 read/write operations,with the test looping one million times.Static variableInstance variableLocal variableSunWirelessToolkit2.1Nokia9210iNokia7650Nokia6600SonyEricssonP90020.93 s36.75 s18.93 s547.34 s48.12 s19.85 s312.35 s24.22 s10.32 s4.56 s2.72 s0.29 s2.61 s1.70 s0.20 sAs can be seen, accessing local variables can be an order of magnitudefaster than accessing variables declared on the heap, and static variablesare generally slower to access than instance variables.342WRITING OPTIMIZED CODEHowever, note that for Sun’s Wireless Toolkit, access to static variablesis faster than to instance variables.

This illustrates something we saidearlier: optimization behavior is platform-dependent.Good design encourages the use of getter and setter methods to accessvariables. As a simple example I might start with an implementation thatstores a person’s age, but later on change this to store their date of birth,calculating their age from the current date. I can make this change if Ihave used a getAge() method, but not if I have relied on a public agefield. But will getter and setter methods not be slower?The following code is used to test the speed of getter and settermethods:private int instanceValue = 6;final int getInstanceVariable(){return instanceValue;}final void setInstanceVariable(int value){instanceValue = value;}long instanceMethodTest(int loop){long timeStart = System.currentTimeMillis();for(int i = loop; --i >= 0; ){...setInstanceVariable(getInstanceVariable());...}return System.currentTimeMillis() - timeStart;}The line setInstanceVariable(getInstanceVariable());was repeated 64 times inside the loop.

Similar code was used to testgetter and setter methods for accessing a static, rather than an instancevariable. In this case, the getter and setter methods and the variablebeing accessed were declared as static. Here are the results for a loopcount of one million (in the case of WTK, extrapolated from a loop countof 100 000):StaticaccessorsInstanceaccessorsSunWirelessToolkit2.1Nokia9210iNokia7650Nokia6600SonyEricssonP9001362.55 s743.44 s457.81 s41.69 s26.07 s1409.42 s1045.16 s628.28 s2.72 s1.78 sSTRINGS343Again we see platform-dependent differences in behavior.

Sun’s WTK,Nokia 9210i and Nokia 7650 are all KVM-based, and on all three thestatic getter and setter accessors are slower than the instance accessors.Of more interest, though, is comparing the time it takes to access aninstance variable directly against accessing it via getter and setter methods.For KVM-based devices, getter and setter methods are very much slower(by about a factor of 20!) However, for CLDC HI-based devices (Nokia6600 and Sony Ericsson P900), there is no difference.

So for the newerdevices, there is no excuse for not using getter and setter methods.What is happening? All method calls are faster after their first execution;the VM replaces lookup by name with a more efficient lookup: virtualmethods are dispatched using an index value into the method table forthe class, while non-virtual methods are dispatched using a direct linkto the method-block for the method. Both approaches offer a similarimprovement; however, non-virtual methods can also be inlined.Public instance methods are virtual.

Final methods may be virtual, butcan never be overridden. So, depending on the type of object referenceto make the call, inlining may still be allowed. Private methods are nonvirtual. Static methods are also non-virtual: they cannot be overridden bya derived class, only hidden. In addition, static methods do not have a‘‘this’’ parameter, which saves a stack push.The VM attempts the actual inlining at runtime after the first execution.It replaces the method call with an inline version of the method if themethod body can be expressed in bytecodes that fit into the methodinvocation bytespace.

In practice this means that simpler getter and settermethods can be inlined by the VM.This optimization was not implemented in the KVM, which explainsthe poor performance of static methods on the earlier phones, but ispresent on the later CLDC HI-based phones.7.8 StringsJava is very careful in how it handles Strings in order to minimizestorage requirements and increase performance. In particular, Stringsare immutable (that is, once a String is created it cannot be modified)and the VM attempts to ensure that there is only one copy of any stringin the String literal pool. This section outlines a number of issues thatarise from this approach.7.8.1 Comparing StringsIn general we use equals() to compare two Strings, for example:if(stringA.equals(stringB)) {/* do something */}344WRITING OPTIMIZED CODEHowever, the expression (stringA == stringB) will generallyreturn true, for example, given:String stringA = "Now is the time";String stringB = "Now is the time";We have to say ‘generally’ because Java JDK 1.1 does not guaranteeto maintain a single copy of identical strings.

We can, however, force theissue by using String.intern(). This method returns a string whichis guaranteed to be unique within the pool.We can therefore do string comparisons using the much faster equality operator:string1 = string1.intern();...string2 = string2.intern();...if(string1 == string2)) {/* do something */}If your application spends a lot of time comparing Strings (particularly common in database applications), this approach can be ofsignificant benefit.Note that String.intern() is not in CLDC 1.0, but has reappearedin CLDC 1.1.7.8.2 Concatenating StringsAs we know, Strings are not mutable; in other words, a String cannotbe modified once it has been created.

So although concatenating stringsis easy, it is also slow. It may be better to use StringBuffer instead.The following code reads in characters one at a time from an InputStream and appends each character to a String:String text = "";while(true){int value = inStream.read();if(value == -1) break;text = text + (char)value;}The highlighted line is doing a lot more work than is apparent. textand value are both converted to StringBuffer, concatenated, thenconverted back to a String. This can be quite a performance hit in atight loop.STRINGS345The following is a better approach:StringBuffer textBuffer = new StringBuffer(256);while(true){int value = inStream.read();if(value == -1) break;textBuffer.append((char)value);}String text = textBuffer.toString();By default a StringBuffer is created with an initial length of16 characters; however, we know we shall be reading at least 256characters, so we set this as the initial capacity.

Характеристики

Тип файла
PDF-файл
Размер
5,73 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Почему делать на заказ в разы дороже, чем купить готовую учебную работу на СтудИзбе? Наши учебные работы продаются каждый год, тогда как большинство заказов выполняются с нуля. Найдите подходящий учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6294
Авторов
на СтудИзбе
314
Средний доход
с одного платного файла
Обучение Подробнее