Scrollbars, part 3: Optimizing the paint cycle

Date:July 29, 2003 / year-entry #7
Tags:code
Orig Link:https://blogs.msdn.microsoft.com/oldnewthing/20030729-00/?p=43033
Comments:    1
Summary:Observe that we paint all 100 lines in our paint handler, even though most of them aren't visible. This is a problem if there are a large number of items, or if painting an item is time-consuming. So instead, we optimize our paint cycle so as to paint only the elements which intersect the paint...

Observe that we paint all 100 lines in our paint handler, even though most of them aren't visible. This is a problem if there are a large number of items, or if painting an item is time-consuming.

So instead, we optimize our paint cycle so as to paint only the elements which intersect the paint rectangle.

void
PaintSimpleContent(HWND hwnd, PAINTSTRUCT *pps)
{
    HFONT hfPrev = SelectFont(pps->hdc, g_hfList);  /* Use the right font */

    int iMin = max(pps->rcPaint.top / g_cyLine, 0);
    int iMax = min((pps->rcPaint.bottom + g_cyLine - 1) / g_cyLine, g_cItems);

    for (int i = iMin; i < iMax; i++) {
        char szLine[256];
        int cch = wsprintf(szLine, "This is line %d", i);
        TextOut(pps->hdc, 0, i * g_cyLine, szLine, cch);
    }

    SelectFont(pps->hdc, hfPrev);
}

Exercise: Explain the formulas for iMin and iMax. Explain why the seemingly equivalent formula

    int iMax = min((pps->rcPaint.bottom - 1) / g_cyLine + 1, g_cItems);

is wrong. Then explain why it doesn't really matter too much.



*DISCLAIMER: I DO NOT OWN THIS CONTENT. If you are the owner and would like it removed, please contact me. The content herein is an archived reproduction of entries from Raymond Chen's "Old New Thing" Blog (most recent link is here). It may have slight formatting modifications for consistency and to improve readability.

WHY DID I DUPLICATE THIS CONTENT HERE? Let me first say this site has never had anything to sell and has never shown ads of any kind. I have nothing monetarily to gain by duplicating content here. Because I had made my own local copy of this content throughout the years, for ease of using tools like grep, I decided to put it online after I discovered some of the original content previously and publicly available, had disappeared approximately early to mid 2019. At the same time, I present the content in an easily accessible theme-agnostic way.

The information provided by Raymond's blog is, for all practical purposes, more authoritative on Windows Development than Microsoft's own MSDN documentation and should be considered supplemental reading to that documentation. The wealth of missing details provided by this blog that Microsoft could not or did not document about Windows over the years is vital enough, many would agree an online "backup" of these details is a necessary endeavor. Specifics include:

<-- Back to Old New Thing Archive Index