Fast Memory Fills and Block Moves in 6502 Assembly

Atari text screen listing five routines with frame counts: fill 1 byte plus pointer 00345, fill (zp),Y pages 00158, fill abs,X unrolled 00074, move (zp),Y pages 00230, move abs,X unrolled 00132; below, a row of letter A and a correctly shifted alphabet

Clearing a screen, copying a character set, scrolling a map, double-buffering a bitmap: many Atari programs spend a surprising part of their time just filling and moving memory. The 6502 has no block instructions, so the speed depends entirely on how the loop is written. The difference between a naive loop and a well-unrolled one is more than four to one. This guide builds five routines, times them on the same 7,680-byte block (the size of a GRAPHICS 8 screen), and explains where the cycles go. It ends with the one rule that matters for overlapping copies.

What you'll learn: the cycle cost of each loop shape, the page loop with (zp),Y, unrolled absolute,X loops and MADS's :n and .rept repeat syntax, how to measure routines with the frame counter, and how to choose the direction of an overlapping move.

What you need: MADS and an emulator, and 6502 Addressing Modes, the Atari Way for the addressing modes used. The test program was assembled with MADS and run in atari800 (NTSC, XL/XE OS). The timings come from the emulator's cycle model.

1. Where the time goes

A loop's cost is its instructions' cycles divided by the bytes each pass handles. Using the 6502's cycle counts:

Loop Instructions per byte Cycles per byte
Store, then increment a 16-bit pointer and compare it LDA #, STA (zp),Y, INC zp, BNE, LDA zp, CMP #, BNE about 24
Page loop STA (zp),Y, INY, BNE (plus a little per page) 11
Unrolled absolute,X, 30 stores per pass 30 × STA abs,X, then INX, BNE about 5.2

Three ideas give most of the speed-up:

  1. Let an index register do the counting. INY/BNE costs 5 cycles, against 13 or more for incrementing and testing a 16-bit pointer.
  2. Use absolute addressing when the address is known. STA abs,X takes 5 cycles, STA (zp),Y takes 6. For stores, neither mode gets slower when crossing a page boundary. Loads with abs,X or (zp),Y take one extra cycle when they cross one, which page-aligned buffers avoid.
  3. Unroll. Repeat the store once for every page, so that one INX/BNE pair serves 30 bytes instead of one.

2. Measuring it

The program runs each routine 50 times with the display switched off (SDMCTL = 0, so ANTIC's screen DMA doesn't distort the result), and reads the frame counter RTCLOK before and after. It starts each measurement on a fresh frame. 50 runs × 7,680 bytes = 384,000 bytes per routine:

Routine Frames for 50 runs Cycles per byte (measured) Predicted One 7,680-byte run
Fill, one byte + 16-bit pointer 345 26.8 24 6.9 frames
Fill, (zp),Y page loop 158 12.3 11 3.2 frames
Fill, abs,X unrolled ×30 74 5.8 5.2 1.5 frames
Move, (zp),Y page loop 230 17.9 16 4.6 frames
Move, abs,X unrolled ×30 132 10.3 9.2 2.6 frames

The measured figures are consistently about 11% above the prediction. That is the time the CPU loses even with the screen off: 9 memory-refresh cycles on every 114-cycle scan line (8%), plus the vertical blank interrupt (see ANTIC DMA and Cycle Timing: Where the CPU's Time Goes). With the screen on, every routine slows by another 30% or so in GRAPHICS 0 or 8.

In practice: a page loop clears a GRAPHICS 8 screen in about three frames, and the unrolled loop does it in one and a half. The naive loop takes seven, long enough to see.

3. The routines

The page loop is the workhorse: short, general, and only twice as slow as the best. Point a zero-page pointer at the start of the block (low byte 0), keep Y running from 0 to 255, and step the pointer's high byte once per page:

fill2   lda #>BUF
        sta PTR+1
        lda #0
        sta PTR
        ldx #PAGES
        ldy #0
        lda #$55
f2      sta (PTR),y
        iny
        bne f2
        inc PTR+1
        dex
        bne f2
        rts

The unrolled loop writes one STA per page. MADS generates them with its repeat syntax: :30 sta BUF+#*256,x expands to 30 lines, where # is the repeat counter (0, 1, 2 …). For a block of several lines, such as the load-and-store pair of a move, use .rept … .endr, which also accepts #. A one-line :n repeat can't contain two instructions with # in both, as we found out when MADS rejected our first attempt. The cost is code size: 30 stores take 90 bytes, and the unrolled move takes 180. The addresses are fixed at assembly time, so for a buffer whose address changes, use self-modifying code (patch the high bytes) or fall back to the page loop.

Partial pages. For a block that isn't a whole number of pages, do the whole pages with one of these loops, then finish the remainder with a short DEY/BNE loop.

4. Overlapping moves: pick the direction

When the source and destination overlap, the order of copying matters. The test program demonstrates this on screen. It puts the alphabet in two buffers, then tries to shift each one place to the right:

  • Copying forward (from the first byte to the last) reads each byte after it has already been overwritten by its left neighbour. The A is copied into the B's place, then that A is copied into the C's place, and so on. The result is the row of 27 A's in the screenshot.
  • Copying backward (from the last byte to the first) moves Z first, then Y, and the alphabet arrives intact, one place to the right.

The rule: if the destination is above the source, copy from the end downwards. If it is below, copy from the start upwards. If the blocks don't overlap, either direction works. Scrolling a screen up (moving data to lower addresses) uses the forward loop, and scrolling it down needs the backward one. A page loop runs backward by starting the pointer at the last page and counting Y down from 255 with DEY and CPY #$FF, or by using a separate counter.

5. The test program

; Timing memory fills and moves: each routine runs 50 times over 7,680
; bytes (a GRAPHICS 8 screen) with the screen off; frames are counted.
RTCLOK  = $12
SAVMSC  = $58
SDMCTL  = $022F
PTR     = $CB               ; 2 bytes
SRC     = $CD               ; 2 bytes
BUF     = $4000             ; 30 pages: $4000-$5DFF
BUF2    = $6000             ; 30 pages: $6000-$7DFF
PAGES   = 30

        org $3000
start   lda SDMCTL
        sta olddma
        lda #0
        sta SDMCTL          ; screen off: no display DMA while timing
        ldx #0
tloop   stx tnum
        lda #50
        sta reps
        lda RTCLOK+2        ; start on a frame boundary
w0      cmp RTCLOK+2
        beq w0
        lda RTCLOK+2
        sta t0
        lda RTCLOK+1
        sta t0+1
rep     ldx tnum
        lda jlo,x
        sta jmpv+1
        lda jhi,x
        sta jmpv+2
jmpv    jsr $FFFF           ; (patched) call routine number tnum
        dec reps
        bne rep
        sec                 ; frames = now - start
        ldx tnum
        lda RTCLOK+2
        sbc t0
        sta flo,x
        lda RTCLOK+1
        sbc t0+1
        sta fhi,x
        inx
        cpx #NR
        bne tloop
        lda olddma
        sta SDMCTL
        jsr report
        jsr overlap
        jmp *

; 1. one byte at a time with a 16-bit pointer
fill1   lda #<BUF
        sta PTR
        lda #>BUF
        sta PTR+1
        ldy #0
f1      lda #$55
        sta (PTR),y
        inc PTR             ; advance the 16-bit pointer
        bne f1b
        inc PTR+1
f1b     lda PTR+1           ; stop at BUF + 7,680 ($5E00)
        cmp #>[BUF+PAGES*256]
        bne f1
        rts

; 2. a page at a time: (zp),Y with Y = 0..255
fill2   lda #>BUF
        sta PTR+1
        lda #0
        sta PTR
        ldx #PAGES
        ldy #0
        lda #$55
f2      sta (PTR),y
        iny
        bne f2
        inc PTR+1
        dex
        bne f2
        rts

; 3. absolute,X with the store unrolled for every page
fill3   ldx #0
        lda #$55
f3      :PAGES sta BUF+#*256,x
        inx
        bne f3
        rts

; 4. block move a page at a time, (zp),Y
move2   lda #>BUF
        sta SRC+1
        lda #>BUF2
        sta PTR+1
        lda #0
        sta SRC
        sta PTR
        ldx #PAGES
        ldy #0
m2      lda (SRC),y
        sta (PTR),y
        iny
        bne m2
        inc SRC+1
        inc PTR+1
        dex
        bne m2
        rts

; 5. block move unrolled with absolute,X
move3   ldx #0
m3
        .rept PAGES
        lda BUF+#*256,x
        sta BUF2+#*256,x
        .endr
        inx
        beq m3x
        jmp m3
m3x     rts

; ---- overlapping moves: shift a string one place to the right ----
overlap ldy #0              ; two copies of the alphabet on rows 10 and 12
ov0     lda alpha,y
        sta row10,y
        sta row12,y
        iny
        cpy #26
        bne ov0
        ldy #0              ; WRONG: forward copy into overlapping area
ov1     lda row10,y
        sta row10+1,y
        iny
        cpy #26
        bne ov1
        ldy #25             ; RIGHT: copy from the end backwards
ov2     lda row12,y
        sta row12+1,y
        dey
        bpl ov2
        lda #0
        sta row12           ; clear the vacated first cell
        lda SAVMSC          ; show both rows
        clc
        adc #<[10*40]
        sta PTR
        lda SAVMSC+1
        adc #>[10*40]
        sta PTR+1
        ldy #26
ov3     lda row10,y
        sta (PTR),y
        dey
        bpl ov3
        clc
        lda PTR
        adc #80
        sta PTR
        bcc ov4
        inc PTR+1
ov4     ldy #26
ov5     lda row12,y
        sta (PTR),y
        dey
        bpl ov5
        rts

; ---- print the frame counts ----
report  ldx #0
rp1     stx tnum
        txa                 ; row x+1, label 20 chars
        clc
        adc #1
        tay
        lda SAVMSC
        clc
        adc rlo,y
        sta PTR
        lda SAVMSC+1
        adc rhi,y
        sta PTR+1
        lda tnum
        asl
        asl
        sta SRC             ; label offset = x*20
        asl
        asl
        clc
        adc SRC
        tax
        ldy #0
rp2     lda labels,x
        sta (PTR),y
        inx
        iny
        cpy #20
        bne rp2
        ldx tnum
        lda flo,x
        sta num
        lda fhi,x
        sta num+1
        ldy #22
        jsr dec5
        ldx tnum
        inx
        cpx #NR
        bne rp1
        rts
dec5    ldx #0              ; 16-bit num as 5 digits at (PTR),y
d1      lda #$10
        sta digit
d2      lda num
        sec
        sbc p10lo,x
        sta tmp
        lda num+1
        sbc p10hi,x
        bcc d3
        sta num+1
        lda tmp
        sta num
        inc digit
        bne d2
d3      lda digit
        sta (PTR),y
        iny
        inx
        cpx #5
        bne d1
        rts

NR      = 5
jlo     dta <fill1,<fill2,<fill3,<move2,<move3
jhi     dta >fill1,>fill2,>fill3,>move2,>move3
labels  dta d'FILL 1 BYTE+POINTER '
        dta d'FILL (ZP),Y PAGES   '
        dta d'FILL ABS,X UNROLLED '
        dta d'MOVE (ZP),Y PAGES   '
        dta d'MOVE ABS,X UNROLLED '
rlo     :24 dta <[#*40]
rhi     :24 dta >[#*40]
p10lo   dta <10000,<1000,<100,<10,<1
p10hi   dta >10000,>1000,>100,>10,>1
alpha   dta d'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
row10   .ds 28
row12   .ds 28
flo     .ds NR
fhi     .ds NR
olddma  dta 0
tnum    dta 0
reps    dta 0
t0      dta a(0)
num     dta a(0)
digit   dta 0
tmp     dta 0
        run start

How it calls the five routines: it patches the address of a JSR from two tables (jlo, jhi) and calls it 50 times. Self-modifying code like this is common and safe in RAM. It would not work in a cartridge.

6. When to use which

  • A one-off clear at start-up: the page loop. It's small and fast enough.
  • Every frame, or a large double buffer: unrolled abs,X, possibly with the screen turned off during loading.
  • Clearing to a pattern: load A with the pattern; the cost is the same.
  • Moving character sets (1K) or player data: unrolled across 4 pages is cheap in code and nearly as fast as it gets.
  • From BASIC: a page-6 routine called with USR, as in Page 6: The Atari's 256 Bytes of Safe Memory, is many times faster than a FOR loop of PEEKs and POKEs.

Troubleshooting

  • The fill overwrites the program: the page count is one too many, or the buffer isn't page-aligned while the loop assumes it is.
  • The copy smears one value across the area: the blocks overlap and the copy runs the wrong way.
  • The unrolled version is slower than expected: loads with abs,X from a buffer that isn't page-aligned pay an extra cycle on every page crossing.
  • MADS: "'#' is allowed only in repeated lines": two instructions with # on a :n line. Use .rept.
  • The timings in your program are worse: the screen is on. Display DMA can take a third of the CPU time.

Further reading

  • The MADS manual: the :n repeat syntax and the .REPT directive.
  • On this site: 6502 Addressing Modes, the Atari Way, ANTIC DMA and Cycle Timing: Where the CPU's Time Goes, Page 6: The Atari's 256 Bytes of Safe Memory, MADS (Mad-Assembler): A Practical Guide for Atari Programmers.

Credits

  • Picture: The test program's results: frames taken by 50 runs of each routine over 7,680 bytes. Below, an overlapping move copied the wrong way (all A's) and the right way. — Program authors; screenshot by the site
  • MADS manual (English) — :n repeat syntax with # counter, .REPT/.ENDR — GitHub project authors
  • Altirra Hardware Reference Manual — 4.14 refresh DMA (9 cycles per scan line), 6502 cycle timing — Avery Lee (Altirra)