Sub topic 4
Heap files: cheap insertion, linear search
A heap file (also called a pile file) stores records in no particular order. A new record goes wherever there is room, usually at the end. This chapter derives the block-access cost of each operation on a heap file. Those costs are the baseline that sorted files and indexes try to beat.
This chapter assumes you can compute the blocking factor and the number of blocks for fixed-length records. That means bfr = floor(B / R) and b = ceil(r / bfr) for unspanned records. It also assumes you know the cost unit is one disk block access.
The working model
A heap file is a sequence of b blocks. Each block holds up to bfr records. The file header keeps the address of the first block and of the last block. Nothing relates a record's position to its key value.
The model has three rules:
- The cost of an operation is the number of blocks read or written.
- Work inside a block in main memory is free.
- The file system can fetch the last block directly through the header, without scanning.
Insertion: constant cost
To insert, the system reads the last block into memory. It appends the record if there is room, then writes the block back. That is 1 read and 1 write, so the cost is 2 block accesses. If the last block is full, the system builds a new block in memory and writes it. That costs 1 access.
The cost does not depend on b. This is the main strength of a heap file.
Search: linear scan
The records are unordered, so the only way to find one is to read blocks one after another. Suppose the search field is a key, so at most one record matches.
- Best case: 1 block access.
- Average case, when the record exists:
b / 2accesses. Each block is equally likely to hold it, so the expected number read is(b + 1) / 2. GATE conventionally writesb / 2. - Worst case, or when the record does not exist:
baccesses.
If the search field is not a key, many records may match. You cannot stop at the first match, so you must read all b blocks every time. A range query such as salary BETWEEN 30000 AND 40000 also reads all b blocks. A heap file has no order to exploit.
Deletion and update
To delete a record, find its block (average b / 2 accesses), remove the record in memory and write the block back (1 access). The average total is b / 2 + 1.
Removing records this way leaves gaps. Real systems usually mark the record as deleted, for example with a deletion bit, and reuse the space later. The file is also reorganised periodically to reclaim space. Deletion therefore costs the same as a search plus one write.
For a fixed-length in-place update, the cost is again search plus one write. For a variable-length update that no longer fits in its block, treat it as delete plus insert.
Reading in key order
A heap file has no key order. To read records sorted by a field, you must run an external sort of the whole file. That costs many more than b accesses. This is why heap files suit workloads that load data in bulk and then scan everything, or that add an index later.
Summary of costs
| Operation | Block accesses |
|---|---|
| Insert | 2 (1 if a new block is started) |
| Search on key, average | b / 2 |
| Search on key, worst case | b |
| Search on non-key field | b |
| Range query | b |
| Delete (find, then write) | b / 2 + 1 on average |
| Read in sorted order | External sort, far more than b |
Worked example
Take B = 1024 bytes, R = 100 bytes and r = 30000 records, unspanned.
import math
def heap_costs(B, R, r):
bfr = B // R # records per block, unspanned
b = math.ceil(r / bfr) # blocks in the file
return {
"bfr": bfr,
"blocks": b,
"insert": 2,
"search_key_avg": b / 2,
"search_key_worst": b,
"search_nonkey": b,
"delete_avg": b / 2 + 1,
}
print(heap_costs(B=1024, R=100, r=30000))The output is {'bfr': 10, 'blocks': 3000, 'insert': 2, 'search_key_avg': 1500.0, 'search_key_worst': 3000, 'search_nonkey': 3000, 'delete_avg': 1501.0}.
Inserting a record costs 2 accesses. Finding one by key costs 1500 on average. The two costs differ by a factor of 750. The next chapters show how sorting and indexing shrink the search cost.
A small simulation
This class counts block accesses for the model above. Each block is a list of records.
class HeapFile:
def __init__(self, bfr):
self.bfr = bfr
self.blocks = []
self.accesses = 0
def insert(self, rec):
if self.blocks and len(self.blocks[-1]) < self.bfr:
self.accesses += 1 # read last block
self.blocks[-1].append(rec)
self.accesses += 1 # write it back
else:
self.blocks.append([rec])
self.accesses += 1 # write the new block
def search(self, key):
for blk in self.blocks:
self.accesses += 1 # read one block
for rec in blk:
if rec[0] == key:
return rec
return None
f = HeapFile(bfr=4)
for k in range(1, 11):
f.insert((k, "row"))
print("insert cost:", f.accesses)
f.accesses = 0
f.search(7)
print("search 7:", f.accesses)
f.accesses = 0
f.search(99)
print("search 99:", f.accesses)It prints 17, 2 and 3. Ten records with bfr = 4 fill 3 blocks. Records 1, 5 and 9 each start a new block at 1 access. The other seven inserts cost 2 each, so the total is 3 + 14 = 17. Record 7 sits in the second block. A missing key forces a read of all 3 blocks.
Common errors
- Using
b / 2for a failed search. A key that is absent requires reading allbblocks. The average ofb / 2applies only when the record is known to exist. - Using
b / 2for a non-key search. A non-key field can match many records, so the scan cannot stop early. The cost isb. - Charging insertion a full scan. A heap insertion never searches, because it does not check for duplicates. If the question requires a uniqueness check on a key, the check costs a full search first.
- Forgetting the write. Deletion and update need the read plus 1 write. Insertion needs 1 read plus 1 write, except when a new block is created.
- Rounding too early. Compute
bfrwith floor andbwith ceiling, then useb. For spanned records,b = ceil(r * R / B), because records may cross block boundaries and no space is wasted.
Exercises
Exercise
A heap file stores r = 100000 unspanned records of R = 128 bytes in blocks of B = 2048 bytes. Find (a) the blocking factor, (b) the number of blocks, (c) the average block accesses to find a record by its key, and (d) the cost of inserting one record when the last block has space.
Show answer
(a) bfr = floor(2048 / 128) = 16. (b) b = ceil(100000 / 16) = 6250. (c) On average, b / 2 = 3125 accesses. (d) 2 accesses: read the last block, then write it back.
Exercise
For the same file, how many block accesses does a search on a non-key field need, and how many does an average deletion of a record found by its key need?
Show answer
A non-key search must read every block, so it needs 6250 accesses. An average key-based deletion needs 6250 / 2 + 1 = 3126 accesses: the search plus one write of the modified block.