Language-dependent Code Optimisation Techniques

Syllabus Point

  • Use a language-dependent code optimisation technique

Code optimisation improves the performance, readability, or efficiency of a program. Techniques are often specific to the language being used.

Python

List comprehensions instead of loops

List comprehensions provide a concise way to create lists and are faster than equivalent for loops because they are optimised at the interpreter level.

  • Replace verbose for loops with a single expression
  • More readable and idiomatic Python
  • Example: [x * 2 for x in range(10)] instead of a for loop with append

Use built-in functions

Python built-in functions (such as sum, map, filter, sorted) are implemented in C and execute faster than equivalent Python code.

  • Built-in functions are optimised at the interpreter level
  • Reduce the need for manual iteration
  • Examples: sum(), min(), max(), len(), sorted(), enumerate()

Avoid global variables to reduce namespace lookups

Python resolves local variable lookups faster than global ones. Excessive use of global variables increases the cost of each access.

  • Local variables are stored in a faster lookup table than globals
  • Pass values as function parameters rather than relying on globals
  • Use constants at module level only where necessary

JavaScript

Minimise DOM access by caching selectors

Accessing the DOM is expensive. Repeated queries for the same element slow performance. Store references to DOM elements in variables instead of querying them repeatedly.

  • Store DOM references in variables: const btn = document.getElementById('submit')
  • Avoid calling querySelector inside loops
  • Batch DOM updates to minimise reflows and repaints

Use asynchronous methods to improve performance

JavaScript is single-threaded. Asynchronous methods (async/await, Promises, callbacks) allow long-running operations to execute without blocking the main thread.

  • Use async/await for network requests and file operations
  • Prevents the UI from freezing during data fetching
  • Use Promise.all() to run multiple async operations in parallel
  • Improves perceived performance and responsiveness

Keep Progressing

Use the lesson navigation below to move through the module sequence.

Language-dependent Code Optimisation Techniques | Testing and Evaluating | Learn Software