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

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

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

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

The StringBuffer willautomatically grow if more characters than this are appended.An alternative to using the + operator to concatenate strings is theString.concat() method. Given strings s1, s2 and s3,s3 = s1.concat(s2)is more than twice as fast as:s3 = s1 + s27.8.3 Using Strings as Keys in Hash TablesStrings are often used as keys in hash tables. Every class, includingString, implements hashCode(), which returns the object’s hashcode and hash table lookups make use of the key’s hash code. However, String.hashCode() recalculates the hash code each time it iscalled. To get around this problem, Larman and Guthrie suggest creating a wrapper class around String, called KeyString, which lookslike this:public final class KeyString{private String key;private int hashCode;public KeyString(String key){setKey(key);}public void setKey(String key){this.key = key;hashCode = key.hashCode();}public int hashCode(){346WRITING OPTIMIZED CODEreturn hashCode;}public boolean equals(Object obj){// See later}}The class caches the hash code rather than recalculating it each time.The use of setKey() allows a KeyString instance to be reused,potentially avoiding unnecessary object creation.If we re-implement hashCode() we are also required to re-implementequals(), and this suggests a further refinement that takes advantage ofthe String.intern() method.First we modify setKey():public void setKey(String key) {this.key = key.intern();hashCode = key.hashCode();}Then we need to implement equals():public boolean equals(Object obj) {if((obj instanceof KeyString)&& (key == ((KeyString)(obj)).key)) return true;else return false;}The if statement first checks that we are comparing two KeyStringinstances.

Because the strings are interned, the if statement’s secondclause can very quickly check if the two KeyString instances areequivalent by comparing the identities of the Strings used as keys.7.8.4The StringBuffer Memory TrapWorking with String and StringBuffer can result in large amountsof memory being used unexpectedly. The problem is this: when StringBuffer.toString() creates a String, the newly created Stringuses the StringBuffer character array. This means that if a StringBuffer with a 1 KB capacity only holds a 10-character string, thenew String will also use a 1 KB character array to store 10 characters.

If the StringBuffer is modified, the StringBuffer array iscopied in its entirety and then modified. Now both the String andSTRINGS347StringBuffer have separate 1 KB character arrays. We have just lostthe best part of 1 KB of memory! Repeating the process will continue touse excessive memory as we generate 10-character strings that use 1 KBcharacter buffers.Here is some code from the Microbench MIDlet that can be run toillustrate the problem:static long bufferTest(int repeat){StringBuffer buffer = new StringBuffer(1024);String[] strings = new String[repeat];Runtime runtime = Runtime.getRuntime();long freeMemory;long timeStart = System.currentTimeMillis();long initialMemory = runtime.freeMemory();for(int loop = repeat; --loop >= 0; ){buffer.insert(0, "" + loop);strings[loop] = buffer.toString();freeMemory = runtime.freeMemory();Test.test.println("Used: " + (initialMemory freeMemory) + ", total: " +runtime.totalMemory() + " " + strings[loop]);initialMemory = freeMemory;}return System.currentTimeMillis() - timeStart;}A sensible value for the repeat argument is 10.

This sets up anarray of 10 strings. Each pass through the loop inserts a character at thebeginning of the StringBuffer, creates a String, and inserts it intothe String array. It then prints out the amount of memory used and thecontents of the buffer, plus the total memory. (Test.test.println()prints a String to a TextBox.)What we find is that each pass through the loop uses 2088 bytes. Thereare 2048 bytes for the 1 KB buffer (Java uses 16-bit Unicode characters),24 bytes for the String (composed of a reference to the character array,a count and an offset into the array) and 16 bytes left over!There is a slight twist to this, though.

If we replace the line:buffer.insert(0, "" + loop);with:buffer.append("" + loop);then each time we go through the loop we only use 24 bytes, insteadof 2088 bytes! What is happening in this case is that we are adding a348WRITING OPTIMIZED CODEcharacter at the end of the StringBuffer array on each pass throughthe loop. This means that each new String can reuse the character arrayfrom the previous String, but with its count value set one greater. (Itis instructive to watch what is happening in a debugger.)7.9 Using ContainersCLDC provides four general-purpose containers: Vector, Stack (whichsubclasses Vector), Hashtable and Array.

The J2SE BitSet class,which provides a container for storing arbitrary-length bit patterns, is notsupported. There are a few issues to be aware of.You should avoid using the default constructors for Hashtable andVector. Java does not specify the default initial capacity and it couldbe bigger than we need. If we only want to store a few items, wedo not want a 1 KB container; this would be of little concern on adesktop computer, but is a serious issue on a mobile phone. BothVector and Hashtable provide constructors that can be used to specifytheir initial size, respectively Vector(int initialCapacity) andHashtable(int initialCapacity).The initial capacity for a Hashtable should be carefully considered.First, the CLDC 1.0 documentation states that ”if many entries are to bemade into a Hashtable, creating it with a sufficiently large capacity mayallow the entries to be inserted more efficiently than letting it performautomatic rehashing as needed to grow the table”.

Secondly, as Larmanand Guthrie point out, to minimize clustering, the size of a Hashtableshould be a prime number and powers of two (e.g. 32, 64, 128) shoulddefinitely be avoided. Given that a Hashtable grows by doubling andadding 1, if we believe our Hashtable needs to grow we should choosean initial capacity that can grow and still be prime. A good candidate is89 (keep doubling and adding 1 and see how long it takes before you get anon-prime number), though 89 may be too large for smaller applications.Both Vector and Hashtable can grow indefinitely.

We mighttherefore be using far more memory than we expect and, perhaps worse,using it unpredictably. We have another problem with the KVM, as usedfor instance on the Nokia 9210 or 7650: although the container shrinksas we remove elements from it or if the container is garbage collected,the recovered memory is only available to our application. The KVMgarbage collector does not make this freed memory available to otherapplications, Java or native. This has changed with the CLDC HI Java VMused on more recent Symbian OS phones: freed memory is returned tothe system on a regular basis.Adding or removing items from Vector and Hashtable can be slow.These containers grow by copying their internal data into a larger array.HOW NOT TO DO IT349Removing an item from the middle of a Vector using removeElementAt(n) is achieved by copying all elements from n to the end of thearray to the preceding slot.Most of the comments we have made for Vector apply to Stack.There is, however, no Stack constructor that sets its initial size, so youneed to use the setSize() method inherited from Vector.A String is frequently used as a key to a Hashtable; however,as we saw in Section 7.8.3, they are not without problems and wesuggested that a wrapper class that stores the hash value of the Stringcould provide faster lookup.

Integers also make useful keys becauseInteger.hashCode() simply returns the Integer value.Finally, think about whether an Array might provide a faster and morememory-efficient container than a Vector or a Hashtable. Vectorcan be extremely slow if it is used incorrectly. In Wireless Java forSymbian Devices, an example based on a first-in first-out queue is given:a vector-based implementation was around 100 times slower than areasonably optimized array-based implementation.7.10 How Not To Do ItWe have discussed a number of ideas for improving the performance ofour code.

This section brings several of these together in an example.The following code is a slightly extreme example of how not to do it.The code goes through a company database extracting information abouteach employee:1234567891011float IMP_TO_MET = 1/2.2;String nameList = "";Vector employees = new Vector();for(int id = 0; id < company.getNumberEmployees(); id = id+1){nameList += company.getCompanyName() + "\t";nameList += company.getEmployee(id).getName() + "\t";nameList += company.getEmployee(id).getWeight() * IMP_TO_MET +"\n";// do something with nameListnameList = "";employees.addElement(company.getEmployee(id));}Here are the problems:• Line 1: IMP_TO_MET should be declared static and final (ignoring for the moment that floats are not available in CLDC 1.0, thoughthey are available in CLDC 1.1)350WRITING OPTIMIZED CODE• Line 3: It is unnecessary to use a Vector, particularly as we can findout the number of employees; an Array would be more appropriate;if we do need to use a Vector, we should at least specify itsinitial size• Line 4: We should dereference company.getNumberEmployeesoutside the loop and use a local variable• Line 4: id++ may optimize better• Line 5: getCompanyName() should be de-referenced outsidethe loop• Lines 6, 7, 10: company.getEmployee(id) should be obtainedonly once inside the loop• Line 6, 7: Should use a StringBuffer.The following code shows how we might resolve these problems.

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

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

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

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