UNIHIVE

Study Hub UNIPORT CSC 288

CSC 288 · Structured Programming

Writing efficient programs

Measuring efficiency with big-O, common growth rates, and practical ways to make programs faster without losing clarity.

Our notes

2 min read

Measuring efficiency

Time on a stopwatch depends on the computer, so we count the basic operations a program performs as the input size n grows, and describe the growth with big-O notation.

Common growth rates

Big-ONameExample
O(1)constantreach a[k]
O(log n)logarithmicbinary search
O(n)linearlinear search, summing an array
O(n log n)linearithmicmerge sort, quicksort on average
O(n²)quadraticselection sort, comparing all pairs
O(2ⁿ)exponentialtrying every subset

Worked example: how growth matters

Suppose one operation takes 1 microsecond. For n = 1,000,000:

  • O(log n): about 20 operations, 20 µs.
  • O(n): 1 s.
  • O(n log n): about 20,000,000, 20 s.
  • O(n²): 10¹², about 11.6 days.

A better algorithm beats a faster computer.

Finding the order of a loop

  • One loop over n items: O(n).
  • A loop inside a loop, both over n: O(n²).
  • A loop that halves its range each time: O(log n).

Example: for i := 1 to n do for j := i to n do ... runs n + (n − 1) + ... + 1 = n(n + 1)/2 times: O(n²).

Practical speed-ups

  1. Choose the right algorithm and data structure (binary search instead of linear on sorted data; a tree or hash table for frequent lookups).
  2. Move unchanging work out of loops: compute length(s) or a constant expression once.
  3. Avoid repeated work: store results you will need again.
  4. Pass large arrays as var or const parameters to avoid copying.
  5. Use integer arithmetic where reals are not needed.
  6. Read files in large pieces, not character by character.
  7. Measure before optimising: find the part that really takes the time (a profiler, or timing statements).

Clarity first

Most of a program's time is spent in a small part of its code. Write clearly first, then improve only the slow parts. "Premature optimisation is the root of all evil" (Knuth, 1974).

Exams usually ask

  • Explain big-O notation and order common algorithms by efficiency.
  • Find the order of a given loop or nested loops.
  • Suggest ways to make a given program more efficient.

Common mistake

Comparing algorithms by timing them once on a small input. On 10 items everything is fast; the growth rate shows on large inputs.

Written by the UniHive team in our own words. Spotted a mistake? Tell us on WhatsApp.

No reading links here yet

Our team adds free books, videos and practice for each topic, and opens every link before it goes up.

All CSC 288 topics

Report

Sign in to report this. It is free.

Is this your work (a lecturer, author or publisher)? Ask us to take it down.