Все вопросы: [micro-optimization]
28 вопросов
Улучшение быстрой сортировки
Если возможно, как мне улучшить следующую быструю сортировку (с точки зрения производительности).Какие-либо предложения? void main() { quick(a,0,n-1); } void quick(int a[],int lower,int upper) { int loc; if(lower<upper) { loc=partition(a,l...
Побитовый XOR и сдвиг целочисленных массивов
Предположим, что битовая последовательность размера M и другая битовая последовательность размера N, где M>> N. И M, и N могут быть сохранены внутри целочисленных массивов: если N имеет длину 30, тогда массив только с одним целым числомбудет необходимо, но если N имеет длину 300, то для ег...
if / else против тернарного оператора
Учитывая время оценки, следующие два эквивалента? if(condition1) { //code1 } else { //code2 } condition1 ? code1 : code2 Или они просто синтаксически разные?
JIT-оптимизация индексатора, который изменяется только последовательно
Мне любопытно, что происходит в этой ситуации: int i = 0; MessageBox.Show(i++.ToString ()); MessageBox.Show(i++.ToString ()); Array[i++] = Foo; Предполагая, что это единственный способ использования i в методе, удаляет ли JIT i и заменяет ли его буквальными значениями?
Какой из этих фрагментов кода на Java работает быстрее?
а) for(int i = 100000; i > 0; i--) {} б) for(int i = 1; i < 100001; i++) {} Ответ находится на этом веб-сайте (вопрос 3).Я просто не могу понять почему ? с веб-сайта: 3. а
CSS micro-optimization
I'm considering micro-optimization of a huge CSS stylesheet and have a couple questions related to that: Is lowercase better than uppercase for reducing file size? Is background-position:right (5 chars); smaller than background-position:0 100%; (6 chars incl whitespace)? Is there anything els...
Optimizing Java code
How can I optimize this code ? I made IPFilter and I need to optimize it. package com.ipfilter; import java.util.HashMap; import java.util.Map; /** * IPFilter * * Loads given IP addresses to memory, so you can easily check if ip addres has been blocked */ public class IPFilter...
Placing index columns on the left of a mysql WHERE statement?
I was curious since i read it in a doc. Does writing select * from CONTACTS where id = ‘098’ and name like ‘Tom%’; speed up the query as oppose to select * from CONTACTS where name like ‘Tom%’ and id = ‘098’; The first has an indexed column on the left side. Does it actually speed things u...
Java, Most Expensive Statements?
What are the most expensive (both in terms of bytecode and cpu cycles) statements in the Java Programming language?
What is faster in Python, "while" or "for xrange"
We can do numeric iteration like: for i in xrange(10): print i, and in C-style: i = 0 while i < 10: print i, i = i + 1 Yes, I know, the first one is less error-prone, more pythonic but is it fast enough as C-style version? PS. I'm from C++ planet and pretty new on Python one.
C pointers vs direct member access for structs
Say I have a struct like the following ... typedef struct { int WheelCount; double MaxSpeed; } Vehicle; ... and I have a global variable of this type (I'm well aware of the pitfalls of globals, this is for an embedded system, which I didn't design, and for which they're an unfortunate but ...
Optimize CSS: Narrow Definition (#mytable tbody span.myclass) better?
I wondered whether or not a 'narrow' definition such as #mytable tbody span.myclass { color: #ffffff; } is better/faster to parse than just .myclass { color: #ffffff; } I read somewhere that narrow definitions supposedly actually have some kind of adversery effect on CSS s...
What is the optimal way for reading the contents of a webpage into a string in Java?
I have the following Java code to fetch the entire contents of an HTML page at a given URL. Can this be done in a more efficient way? Any improvements are welcome. public static String getHTML(final String url) throws IOException { if (url == null || url.length() == 0) { throw new Il...
PHP Function execution cost table
There is a reference table that shows the execution cost of every php function? I know that the time execution is boundet to many factors and is impossible to determinate an unique value, but im looking for a 'ideological' table. For example, is_dir() = cost 3 is_file() = cost 2 (take it JUS...
Smart JVM and JIT Micro-Optimizations
Over time, Sun's JVM and JIT have gotten pretty smart. Things that used to be common knowledge as being a necessary micro-optimization are no longer needed, because it gets taken care of for you. For example, it used to be the case that you should mark all possible classes as final, so the JVM ...
Does using xor reg, reg give advantage over mov reg, 0?
There're two well-known ways to set an integer register to zero value on x86. Either mov reg, 0 or xor reg, reg There's an opinion that the second variant is better since the value 0 is not stored in the code and that saves several bytes of produced machine code. This is definitely good - ...
Fast Euclidean division in C
I am interested in getting the remainder of the Euclidean division, that is, for a pair of integers (i, n), find r such as: i = k * n + r, 0 <= r < |k| the simple solution is: int euc(int i, int n) { int r; r = i % n; if ( r < 0) { r += n; } return r; } ...
C coding practices for performance or code size - beyond what a compiler does
I'm looking to see what can a programmer do in C, that can determine the performance and/or the size of the generated object file. For e.g, 1. Declaring simple get/set functions as inline may increase performance (at the cost of a larger footprint) 2. For loops that do not use the value of the l...
Does the order of cases matter in PHP switch statements?
In PHP switch statements, does placing more common cases near the top improve performance? For example, say the following function is called 1,000 times: <?php function foo_user ($op) { switch ($op) { case 'after_update': //Some Stuff case 'login': //Som...
array_push () vs. $ array [] = .... Что быстрее всего?
Мне нужно добавить значения, полученные из MySQL, в массив (PHP). Вот что у меня есть: $players = array(); while ($homePlayerRow = mysql_fetch_array($homePlayerResult)) { $players[] = $homePlayerRow['player_id']; } Это единственный способ сделать это? Также , что следующее быстре...
Разница между n = 0 и n = n - n
Когда я читаю этот вопрос. Я вспомнил, как кто-то однажды сказал мне (много лет назад), что с точки зрения ассемблера эти две операции очень разные: n = 0; n = n - n; Верно ли это, и если это так, то почему? РЕДАКТИРОВАТЬ: Как отмечается в некоторых ответах, я полагаю, что компи...
как ни странно, это, вероятно, проблема с переполнением стека
Следующая процедура (объяснение следует) отлично работает для действительно небольших списков, но когда список содержит большее количество элементов (1/2 миллиона), приложение переходит в состояние «не отвечает», и для завершения требуется около 2,5 минут. (очень плохое время). Я мог бы добавить...
Ускоряет ли цикл перестановка условной оценки?
Немного странный: недавно друг сказал мне, что в этом примере цикл for был изменен с: for(int i = 0; i < constant; ++i) { // code... } кому: for(int i = 0; constant > i; ++i) { // code... } немного повысит производительность в C ++. Я не понимаю, почему сравнение пост...
Оптимизировать алгоритм двоичного поиска
В бинарном поиске у нас есть два сравнения: одно для большего, а другое для меньшего. чем, иначе это среднее значение. Как бы вы оптимизировали, чтобы нам нужно было проверять только один раз? bool binSearch(int array[], int key, int left, int right) { mid = left + (right-left)/2; if...
Какой самый эффективный способ выполнять побитовые операции в массиве C
У меня есть массив C, например: char byte_array[10]; И еще один, который действует как маска: char byte_mask[10]; Я хотел бы получить еще один массив, который является результатом первого и второго, используя побитовую операцию для каждого байта. Как это сделать наиболее эффекти...
Оптимизация C ++ для отрицательных целых чисел
Допустим, у нас есть отрицательное целое число, скажем int a; есть ли более быстрая реализация -а? Нужно ли мне проделать с этим побитовую операцию?
Скорость CSS
Это просто вопрос, который поможет мне лучше понять рендеринг CSS. Допустим, у нас есть миллион строк этого. <div class="first"> <div class="second"> <span class="third">Hello World</span> </div> </div> Какой самый быстрый способ изме...
Следует ли использовать Java String.format (), если важна производительность?
Мы должны постоянно создавать строки для вывода журнала и т. д. В версиях JDK мы узнали, когда использовать StringBuffer (многие добавления, потокобезопасные) и StringBuilder (многие добавления, небезопасные для потоков). Какой совет по использованию String.format()? Насколько это эффективно,...