Archive for June, 2010

Using QString effectively

June 22nd, 2010 No comments

QLatin1String : Avoid mallocs in operator ”==”

Creating a QString from a C-string involves a malloc. For example, there is a hidden-malloc cost in the following code.
if (fruit== "apple") { ... } // hidden malloc
In the code above, “apple” gets converted into a QString using QString::fromAscii(). This means that QString will allocate memory for the string “apple” and creates a deep copy of the C-style string. This deep copy is not really necessary and can be avoided by not creating a QString to start with and if the encoding of the C-string was somehow known. Since Latin-1 string comparisons are most common, Qt provides a special class called QLatin1String that just holds a pointer to the C-string provided in it’s constructor. In addition, QString provides a QString::operator==(const QLatin1String &) overload that has special code to compare without malloc+deep copy. We can make the above code fast by writing it instead as,
if (fruit== QLatin1String("apple")) { ... } // fast and mentions encoding

QStringRef : String manipulation without the malloc

QString has various methods for string manipulations like mid(), left(), right(). All of them create a new QString and hence a malloc/deep copy of data in an existing QString. Instead, one can use QString::midRef(), QString::leftRef() and QString::rightRef() to obtain a QStringRef. A QStringRef is a reference of a portion of a QString. QString also provides many overloads like QString::operator==(const QStringRef &) for optimizations with QStringRef.

QString::reserve and QString::squeeze

If you expect a QString to grow, it’s better to call QString::reserve to allocate extra memory in advance so that every call to QString::append() does not result in a malloc. Extra memory can be reclaimed using QString::squeeze.

QStringBuilder : Fast QString concatenation

The code below requires atleast 2 mallocs.
if (foo.startsWith("(" + type + ") 0x"))
Qt 4.6 introduces an internal class called QStringBuilder that “reserves” memory for a concatenation chain in a single shot. It does so by having each of the + operations above return a different class (not QString). This class keeps track of the string’s that are being appended and the required memory at each step. At the final step, where the concatenation operation gets converted into a QString it allocates memory in a single shot and copies all the strings in the chain one after another. This features can be enabled by using QT_USE_FAST_CONCATENATION. With this defined, one can use the operator ’%’ instead of ’+’. One would now write,
if (foo.startsWith("(" % type % ") 0x"))
If we want to use ’+’ itself instead of ’%’, one can also define QT_USE_FAST_OPERATOR_PLUS. See Fast concatenation for more details

Use QStringMatcher to match a string repetitively

If you are looking for a string repetitively in many strings or in the same string many times, you should use QStringMatcher. It uses Boyer-Moore string search algorithm to perform fast searches.


June 22nd, 2010 No comments

The QtService component is useful for developing Windows services and Unix daemons.

The project provides a QtService template class that can be used to implement service applications, and a QtServiceController class to control a service.

On Windows systems the implementation uses the Service Control Manager.

On Unix systems services are implemented as daemons.


Single Application

June 19th, 2010 No comments

The QtSingleApplication component provides support for applications that can be only started once per user.

For some applications it is useful or even critical that they are started only once by any user. Future attempts to start the application should activate any already running instance, and possibly perform requested actions, e.g. loading a file, in that instance.

The QtSingleApplication class provides an interface to detect a running instance, and to send command strings to that instance.

For console (non-GUI) applications, the QtSingleCoreApplication variant is provided, which avoids dependency on QtGui.


Download Open Source Edition (LGPL):


June 18th, 2010 No comments

QThread was designed and is intended to be used as an interface or a control point to an operating system thread, not as a place to put code that you want to run in a thread. We object-oriented programmers subclass because we want to extend or specialize the base class functionality. The only valid reasons I can think of for subclassing QThread is to add functionality that QThread doesn’t have, e.g. perhaps providing a pointer to memory to use as the thread’s stack, or possibly adding real-time interfaces/support. Code to download a file, or to query a database, or to do any other kind of processing should not be added to a subclass of QThread; it should be encapsulated in an object of it’s own.

You’re doing it wrong…

// create the producer and consumer and plug them together
Producer producer;
Consumer consumer;

bool bOk = producer.connect(&consumer,
bOk = consumer.connect(&producer,
                       SIGNAL(produced(QByteArray *)),
                       SLOT(consume(QByteArray *)));

// they both get their own thread
QThread producerThread;

QThread consumerThread;

// go!

Reference: Threading without the headache or QThread’s no longer abstract (see attached file)

Lies, damned lies and statistics (about TEDTalks)

June 17th, 2010 No comments

In a brilliantly tongue-in-cheek analysis, Sebastian Wernicke turns the tools of statistical analysis on TEDTalks, to come up with a metric for creating “the optimum TEDTalk” based on user ratings. How do you rate it? “Jaw-dropping”? “Unconvincing”? Or just plain “Funny”?


Tags: , ,

debug assertion in Delphi 2009 on Windows 7 64-bit

June 9th, 2010 No comments

Using Delphi 2009 on Windows 7 64-bit you can notice about the error dialog during debugging:

Assertion failure: “(!”SetThreadContext failed”)” in ..\win32src\thread32.cpp

The problem is that the executable file is blocked and Delphi 2009 studio must be closed.

The solution is:

Open bordbk120N.dll in any HEX editor and change 1 byte at offset 245181 (0x3BDBD) from 0x74 to 0xEB. This works very well with bordbk120N.dll version


Kanban для одного

June 3rd, 2010 No comments

Что же такое Kanban? Чтобы не запутывать, скажу, что упрощая, систему можно свести к 3-м правилам:

  • Визуализируй состояние (Kanban-доска)
  • Ограничь количество слотов в каждом из состояний
  • Измеряй скорость работы, т.е. среднее время исполнения одной задачи

Задачи переходят из левых колонок в правые, не перескакивая. Приоритизация задач осуществляется в колонке todo, в которую я рекомендовал бы помещать только «большие» задачи: мелочь пусть просачивается между большими, как и положено. Что означают остальные колонки?

  • wip — work in progress, то, что я сейчас делаю.
  • review — анализ выполненных задач, проверка качества, в программировании это называлось бы «тестированием»
  • done — сюда попадают задачи, успешно прошедшие предыдущую колонку. Зачем нужна такая колонка? Объясню, зачем она мне: я знаю за собой особенность, я порой не произвожу «доставку» выполненной работы

Цифры под заголовками — те самые слоты. Они означают, что больше этого числа помещать в колонку нельзя. Эти цифры могут меняться, они просто обязаны меняться.

После каждой «доставки» — например, отправки клиентам выполненной работы, стоит делать «ретроспективу», во время которой обязательно нужно проанализировать, что мешало выполнить работу максимально эффективно и поставить себе задачи на исправление этих «узких мест». При достижении ограничений в любой из колонок, вам стоит бросить все силы на освобождение «слота».


10+1 things they never teach in college about programming

June 2nd, 2010 No comments

Written by Alberto Gutierrez:

I still remember how naive I was just after I finished my studies. I was convinced that I was ready to join any software company and start shining as a top class developer. Obviously, no long after I started working, I realized how many things I didn’t know.

As I have been acquiring experience, I have been learning things the hard way, stuff which I was never taught, and which its understanding, is basic to become a good developer. This is my list of the 10 things I wish I had been taught.

  1. We’re always wrong
  2. If something can break, it will break
  3. All code is crap
  4. There is always a bug
  5. The most important thing is the client
  6. Design on paper doesn’t work
  7. Less is more
  8. Coding is only 20% of what we do
  9. The customer doesn’t know what he/she wants NEVER!
  10. Someone has done it before

Bonus: Hey! Our job is cool!