Key Takeaways
Let the page appear before JavaScript takes over the browser
Scripts can stall the page. In the browser model described here, JavaScript execution shares a process with page rendering and user-interface updates. When the browser meets a script tag, it may need to download and run that code before continuing to parse the page. Several scripts placed near the top can mean a long wait before anything appears onscreen.
Load with the user in mind. Put ordinary scripts near the end of the page, reduce the number of separate files by combining code in dependency order, and consider dynamically loading less urgent code after the initial page is ready. Dynamic loading avoids blocking the page, but files that depend on one another still need reliable execution order. Fewer requests help, yet one enormous script can also delay the page if it runs all at once.
What's important is the distinction between a page being complete and a page becoming useful. Users can begin reading before every feature has arrived, so loading strategy is also a product decision: prioritize what makes the first view work, then bring in secondary behavior. The book's browser examples date from an earlier era, and exact loading behavior varies across browser generations. The durable principle is to inspect the actual critical path, not to treat any single script-placement rule as a substitute for testing.
Profile the bottleneck users feel, not the code that looks suspicious
Find the expensive stage. A slow page may be waiting on a network request, parsing a script, executing a function, or recalculating layout. The book recommends using both profilers and network analyzers rather than guessing. A profiler can reveal which functions consume time and how often they run; a network waterfall shows when scripts and other assets arrive, and whether one request delays another.
Measure deliberately. Simple timers can compare two implementations, while tools such as Firebug, browser developer tools, Fiddler, and YSlow offer deeper views of execution and delivery. Test representative browsers and realistic inputs. For regular expressions, include strings that nearly match but ultimately fail, since those can expose costs that easy successes conceal.
Profiling turns optimization from aesthetic preference into diagnosis. It also encourages a useful systems view: the slowest function is not necessarily the user-facing bottleneck if the browser is waiting on the network or layout work. Measurements can mislead, though. Tiny tests exaggerate timing noise, while synthetic workloads may not resemble real traffic. Good performance work therefore pairs local measurements with user-visible outcomes and repeats tests under conditions that resemble the devices and connections the application must serve.
Cross into the DOM sparingly, and batch every visible change
DOM work carries overhead. JavaScript and the browser's document model are separate systems, so repeated access across their boundary can cost more than ordinary calculations. In one example, repeatedly appending characters to an element during a 15,000-iteration loop was dramatically slower than building the string in JavaScript and updating the element once. The book reports a 155-fold difference in Internet Explorer 6.
Avoid needless layout work. A reflow recalculates element geometry; a repaint redraws affected pixels. Reading layout measurements after changing styles can force pending changes to be applied immediately. Cache collection lengths and repeated element references, build new content in a document fragment, and apply related style changes together. Event delegation also reduces overhead by letting one parent handler respond to events bubbling up from many children.
The DOM lesson resembles a general systems principle: boundary crossings are costly even when each individual crossing seems trivial. Batching is effective because it lets the browser combine work rather than repeatedly invalidating its layout. This is particularly valuable in interfaces with large lists or frequent updates. Still, minimizing DOM calls should not become a fetish. The best approach depends on which operations trigger layout, how much content changes, and whether code remains understandable and maintainable.
Cache repeated lookups, but keep closures and dynamic scope deliberate
Make frequent access cheap. JavaScript resolves identifiers by searching a scope chain, the ordered set of environments where a function can find its variables. Local variables are close at hand; globals and other out-of-scope values can require more searching. Saving a frequently used global such as the document object in a local variable, or saving a repeatedly read object property, avoids repeated lookups. Nested object paths can multiply that work.
Watch hidden costs. A closure lets a function keep access to variables from its surrounding function, but that retained environment can use more memory and make some lookups slower. The book also warns that with and eval can make scope dynamic, limiting some engine optimizations. These costs matter most in hot code paths, so simplify repeated access where profiling shows it matters rather than rewriting every readable expression.
This is a useful reminder that abstraction has a runtime shape. Closures are not inherently poor design: they are central to many clean event and callback patterns. The relevant question is whether a retained environment or repeated property access creates meaningful cost in a frequently executed path. Local caching can help, but it can also obscure changing values or create stale assumptions. Performance and correctness need to be considered together, especially when code relies on object methods whose behavior depends on this.
Choose algorithms that avoid work, not clever loops for their own sake
Reduce total work first. The book finds ordinary for, while, and do-while loops broadly similar in speed, while for-in can be much slower because each pass searches object properties. For a known set of array items, cache the length, reduce unnecessary operations inside the loop, and consider whether every item must be processed. Historical tests reported gains from loop unrolling at very large iteration counts, but such tricks are not automatically worthwhile for smaller workloads.
Reuse results and simplify decisions. A lookup table can replace a long chain of tests when each key maps to a result. Memoization means saving previous calculation results so repeated requests can reuse them. It can reduce redundant work in recursive calculations, while converting recursion to iteration can avoid browser call-stack limits. The practical choice depends on input size, repetition, and readability.
The strongest idea here is algorithmic economy, not code golf. Saving a repeated calculation can matter far more than shaving an operation from a loop, and a lookup table can make both execution and intent clearer. Yet a cache has costs too: memory use, invalidation, and the possibility that inputs change. Older benchmark claims, including gains from loop unrolling, should be treated as hypotheses for testing on current engines, not as universal instructions.
Design strings and regexes to avoid repeated copying and backtracking
String costs depend on the engine. The book's cross-browser tests found that older Internet Explorer versions handled repeated string concatenation poorly. For many concatenations there, collecting pieces in an array and joining them avoided repeatedly copying a growing string. Other browsers often optimized the plus operators better, so the best method depended on the target engines.
Make regex failure cheap. A regular expression may try many alternative paths when a match fails. Runaway backtracking occurs when those possibilities multiply, especially with nested quantifiers or overlapping alternatives. The book shows a pattern that can require more than a billion backtracking steps on a string of 20 repeated characters. Make patterns specific, avoid ambiguous overlap, and test long partial matches. For literal searches, methods such as indexOf or charAt may be simpler and faster than a regex.
Regular expressions are compact descriptions of search, but their brevity can conceal a large search tree. The key safety question is not only whether a pattern matches valid input, but how much work it does on malformed or almost-valid input. That makes adversarial test cases important for any interface processing user-supplied text. Concatenation advice is more engine-dependent: the chapter captures real differences among browsers of its time, but modern implementations should be measured rather than assumed to behave the same way.
Keep each UI-thread task below 100 milliseconds
Long tasks make interfaces feel broken. In the browser model presented here, JavaScript and interface updates take turns. While a long script is running, the browser may not respond promptly to clicks, redraws, or other input. The book uses 100 milliseconds as an upper bound for a continuous task, drawing on research about response time and perceived direct control.
Yield instead of freezing. Timers can divide long work into smaller tasks, allowing the browser to update between them. Process items in batches rather than one per timer: the book estimates that handling 1,000 one-millisecond items individually with 25-millisecond delays could take 26 seconds, while batches of 50 could finish in about 1.5 seconds. Web workers can move suitable data-heavy work, such as parsing a large JSON string, off the interface thread.
Responsiveness is not simply a matter of finishing quickly. A task that takes longer overall can still feel better if the interface remains available while it runs. That is a scheduling problem as much as a speed problem. Chunking works well when work can be paused safely; workers fit computations that do not need direct access to the page. The 100-millisecond threshold is a practical guideline from the book's sources, not a guarantee that every task below it will feel instantaneous on every device.
Choose Ajax transport and format by control, payload, and trust
Match the channel to the job. XMLHttpRequest offers control over requests and responses, but the book's examples restrict it to the page's domain and treat returned data as text or XML. Dynamic script insertion can request across domains and execute JavaScript directly, but offers less control and grants the imported code access to the page. Image beacons are a lightweight way to send small amounts of data without needing a response body.
Keep payloads lean. XML can be verbose and expensive to parse. JSON is compact and maps naturally to JavaScript data, while a character-delimited custom format can be smaller still for large datasets. In one test, the custom format took about 78 milliseconds overall for a roughly 223-kilobyte dataset. JSON-P, executable JSON wrapped in a callback, can parse quickly, but must not carry sensitive data.
Ajax optimization is a three-way negotiation among bandwidth, client computation, and security. A smaller format may save download time while requiring custom parsing; executable responses may reduce parsing but broaden the trust boundary. Those tradeoffs are more durable than any ranking from a single benchmark. Custom formats can be efficient, but their implicit field order and delimiters require disciplined versioning and validation. Choosing the fastest transport without considering who controls the response can turn a performance win into a security failure.
Build for the network: fewer requests, smaller files, smarter caching
Treat delivery as part of performance. A production build can combine JavaScript files, remove comments and unnecessary whitespace, and compress text responses with gzip. The book reports that gzip often reduced payload size by about 70 percent. Combining files can reduce request overhead, while careful ordering preserves dependencies. Build tools can automate these steps so developers do not have to repeat them manually.
Make repeat visits cheaper. Cacheable static files can avoid unnecessary downloads, and versioned filenames let updated assets bypass stale cached copies. A content delivery network can serve files closer to users and reduce network delay. The book cites research in which Yahoo's home page, with a full cache, required 90 percent fewer requests and 83 percent fewer bytes than with an empty cache. Caching strategy must account for users whose browsers have limited storage.
This chapter widens the definition of JavaScript performance: code quality cannot compensate for avoidable network trips or oversized production assets. Build automation makes good delivery practices repeatable, while versioned filenames resolve the tension between long-lived caching and timely updates. The precise benefits depend on traffic patterns, cache behavior, and infrastructure. Compression and concatenation should be measured together, and deployment pipelines should preserve source maps or another debugging path so production efficiency does not make failures needlessly opaque.
Remove repeated interpretation before tuning individual JavaScript operations
Avoid evaluating strings as code. The book calls the extra parsing and compilation caused by eval, the Function constructor, or string arguments to timers double evaluation. In its historical benchmark, reading 10,000 array items through eval took about five seconds in Internet Explorer 7, compared with roughly 31 milliseconds using ordinary code. Pass functions to timers and avoid dynamic evaluation when a direct function call will do.
Let the language and browser do their work. Object and array literals are typically faster and shorter than constructing empty containers and assigning each member separately. Detect browser capabilities once, either when a function is first called or during setup, instead of repeating the same test every time. Prefer native operations when they fit the task, but test results and maintain clarity before applying micro-optimizations such as bitwise substitutions.
The broad principle is to eliminate entire categories of unnecessary work before polishing individual instructions. Repeated interpretation and repeated feature detection are especially attractive targets because removing them can improve many calls at once. The book's striking eval timings also show why averages across browsers can hide severe outliers. However, native code is not automatically the best choice if it changes behavior or impairs portability. An optimization is only successful when it preserves correctness and improves the workload that actually matters.
Analysis
The book's central argument is that JavaScript performance is a property of the whole browser experience, not merely the speed of executing language expressions. A page can be delayed by synchronous script loading, repeated crossings into the DOM, layout recalculation, expensive algorithms, serialization, network latency, or careless deployment. That broad view remains the work's most valuable contribution: it makes the developer responsible for the path from bytes arriving to the interface responding.
Its structure follows that path from loading, through code and interaction, to Ajax, production delivery, and measurement. This breadth makes compression difficult. Some advice concerns enduring costs, such as excessive work, blocking interaction, or ambiguous regexes. Other advice is tied closely to browser implementations from 2010. The book itself repeatedly shows why such distinctions matter: a technique can be faster in one engine and slower in another. Historical timings should therefore be read as demonstrations of mechanisms, not as current performance guarantees.
The strongest practical method is a cycle: identify the user-visible delay, isolate whether it comes from network, execution, DOM work, or rendering, change one cause, and measure again under representative conditions. This prevents a common failure of optimization, which is spending days on code that is not on the critical path. It also explains why the book gives so much attention to profiling and network analysis rather than only to clever syntax.
A useful tension runs through the advice. Caching lookups, consolidating files, or using custom formats can improve speed, but they can also increase coupling, complexity, or security risk. Performance is not a single number detached from maintenance and correctness. The most defensible lesson is to optimize the measured bottleneck while protecting the user's ability to interact and the team's ability to understand the system.
Review Summary
High Performance JavaScript receives mixed reviews, with an average rating of 4.11 out of 5. Many readers praise its detailed insights and practical tips for optimizing JavaScript code. However, some criticize its outdated content, as the book was published in 2010. Positive aspects include thorough explanations of performance techniques, DOM interactions, and regular expressions. Critics note that many practices are now standard and that browser benchmarks are obsolete. Despite its age, some readers still find value in the fundamentals and historical perspective on JavaScript performance optimization.
People Also Read
Glossary
Scope chain
Ordered variable lookupThe sequence of environments a JavaScript function searches to resolve a variable name. The function's local environment is searched first, followed by surrounding environments and eventually the global environment. The book explains that lookups farther along this chain could be slower in many engines of its era, and that dynamic scope constructs can complicate optimization.
Reflow
Layout recalculationA browser operation that recalculates the geometry and positions of elements after a change affects page layout. Adding content, changing dimensions, or moving elements can trigger reflow. Because recalculation may affect neighboring elements or much of the page, repeated changes and requests for fresh layout measurements can make an interface less responsive.
Event delegation
Parent handles child eventsA technique that attaches one event handler to a parent element instead of separate handlers to many child elements. Browser events bubble from the target toward ancestors, allowing the parent handler to inspect which child was involved. This can reduce handler setup work and memory use on pages with many interactive elements.
Duff's Device
Loop unrolling techniqueA loop-unrolling method that performs several units of work during each loop pass, reducing the number of loop-control iterations. The JavaScript version described in the book processes items in groups, commonly eight at a time. Its benefit depends on workload size and engine behavior, so it is not a general replacement for ordinary loops.
Memoization
Cache prior calculationsA technique that stores the results of earlier function calculations and returns a saved result when the same input appears again. In recursive algorithms, this can avoid repeating subproblems. The book illustrates the method with factorial calculations and notes that caching adds memory use and is most useful when calculations recur.
Runaway backtracking
Explosive regex searchA regular expression performance failure in which the engine explores a rapidly growing number of possible ways to match a string before concluding that no match exists. Ambiguous alternatives and nested quantifiers can create this problem, especially on long strings that nearly match. Specific patterns and tests with partial matches help expose and prevent it.
JSON-P
Executable JSON callbackJSON data wrapped in a JavaScript callback so it can be loaded through a dynamically inserted script element. Because the browser executes the response as code, this approach can avoid parsing a returned JSON string and can request data across domains in the historical browser environment described. The same executability creates a security risk, so sensitive data should not be exposed this way.
Multipart XHR (MXHR)
Many resources, one requestA technique that packages multiple resources into one XMLHttpRequest response, separates them with delimiters, and reconstructs them in the browser. It can reduce the number of HTTP requests, particularly for resources used on only one page. The book notes that reconstructed resources are not individually placed in the browser cache and that robust streaming support complicates implementation.
Web workers
Background JavaScript threadsA browser feature that runs JavaScript in a worker environment separate from the page's user-interface thread. Workers cannot directly manipulate the page DOM, so they communicate with page code by sending messages. They suit lengthy computations on data, such as parsing or sorting, when keeping the interface responsive is more important than sharing the same execution context.
FAQ
What's High Performance JavaScript about?
- Focus on Performance: High Performance JavaScript by Nicholas C. Zakas is centered on optimizing JavaScript to enhance web application performance, addressing execution time, DOM interaction, and network latency.
- Historical Context: The book provides a historical perspective on JavaScript, tracing its evolution from 1996 to the present, highlighting the increasing complexity of web applications.
- Practical Techniques: It offers practical techniques and best practices for writing efficient JavaScript code, making it a valuable resource for developers aiming to improve their skills.
Why should I read High Performance JavaScript?
- Enhance User Experience: By applying the techniques in this book, you can significantly improve the speed and responsiveness of web applications, leading to a better user experience.
- Stay Current: The book covers the evolution of JavaScript engines and optimization practices, ensuring you are up-to-date with the latest trends in web development.
- Expert Insights: Authored by Nicholas C. Zakas, a recognized expert, the book provides valuable insights that can help you become a more proficient JavaScript developer.
What are the key takeaways of High Performance JavaScript?
- Optimization Techniques: The book outlines various optimization techniques, such as minimizing DOM access and using efficient algorithms, to improve JavaScript performance.
- JavaScript Loading Strategies: It emphasizes efficient JavaScript loading, recommending practices like placing scripts at the bottom of the page to avoid blocking rendering.
- Understanding JavaScript Engines: Readers gain insights into modern JavaScript engines, including just-in-time compilation and garbage collection, crucial for writing high-performance code.
What are the best quotes from High Performance JavaScript and what do they mean?
- Performance and Usability: "JavaScript performance in the browser is arguably the most important usability issue facing developers." This highlights the critical role of performance in user satisfaction and web application success.
- Minimize DOM Interaction: "Touch the DOM lightly, and stay within ECMAScript as much as possible." This advice emphasizes minimizing direct DOM interactions, which can be slow, and focusing on faster JavaScript operations.
- Comprehensive Techniques: "The techniques and approaches taught in this book address many different aspects of JavaScript." This indicates the book's comprehensive nature, covering essential topics for optimizing JavaScript performance.
How does High Performance JavaScript address DOM scripting performance?
- DOM Access Costs: The book explains that accessing and modifying DOM elements is expensive and can lead to performance bottlenecks, especially in loops.
- Batch DOM Changes: It advises batching DOM changes to minimize reflows and repaints, which can slow down the user interface.
- Efficient Methods: The author recommends using methods like
document.createDocumentFragment()to make off-document changes before appending to the DOM, reducing reflows.
What are the best practices for loading JavaScript according to High Performance JavaScript?
- Scripts at the Bottom: The book recommends placing all
<script>tags just before the closing</body>tag to ensure the page renders before JavaScript execution begins. - Asynchronous Loading: It suggests using the
asyncordeferattributes for script tags to prevent blocking the rendering of the page while scripts are being downloaded. - Minimize Script Tags: Grouping multiple scripts into a single file reduces the number of HTTP requests, significantly improving loading times.
What techniques does High Performance JavaScript recommend for optimizing algorithms?
- Minimize Work Per Iteration: The book advises reducing operations within loops to improve performance, such as caching array lengths in local variables.
- Efficient Data Structures: It suggests using lookup tables instead of conditionals for mapping values, which can significantly speed up execution.
- Avoid Recursion: The author recommends using iterative solutions instead of recursive ones to prevent stack overflow errors and improve performance.
How does High Performance JavaScript explain the importance of understanding JavaScript engines?
- Engine Evolution: The book discusses the evolution of JavaScript engines and their performance improvements through techniques like just-in-time compilation.
- Garbage Collection: It explains how garbage collection works in different engines and its impact on performance, emphasizing the need for memory-efficient code.
- Performance Implications: Understanding engine execution helps developers write optimized JavaScript, leading to faster web applications.
How does High Performance JavaScript address the browser UI thread?
- Single Process Management: The book explains that most browsers have a single process shared between JavaScript execution and UI updates, which can lead to unresponsive interfaces if not managed properly.
- Task Queuing System: Zakas describes how the UI thread uses a queuing system to manage tasks, helping developers optimize code to ensure UI updates are not blocked.
- Responsiveness Importance: Ensuring responsiveness in web applications is critical, and developers are encouraged to minimize JavaScript execution time to keep the UI responsive.
What techniques does High Performance JavaScript recommend for optimizing Ajax?
- Efficient Data Formats: The book recommends using JSON instead of XML for Ajax requests due to its lightweight nature and faster parsing.
- Minimize HTTP Requests: Zakas advises combining multiple Ajax requests into a single request whenever possible to decrease load times.
- Leverage Caching: Properly configured caching can reduce server load and improve response times for repeat users.
How can I improve my JavaScript code based on High Performance JavaScript?
- Avoid Double Evaluation: The book advises against using
eval()and theFunction()constructor due to performance penalties, recommending direct function calls instead. - Object and Array Literals: Zakas emphasizes the performance benefits of using object and array literals for creating data structures, resulting in cleaner code.
- Implement Lazy Loading: Using lazy loading techniques defers work until necessary, optimizing performance by executing only essential code during critical interactions.
What are the performance implications of using web workers as discussed in High Performance JavaScript?
- Offload Processing: Web workers allow JavaScript code to run in the background, separate from the main UI thread, improving performance by offloading heavy computations.
- Limited DOM Access: Web workers cannot directly access the DOM, preventing UI-related issues and ensuring long-running tasks do not interfere with user interactions.
- Efficient Communication: Web workers communicate with the main thread using the
postMessage()method, allowing efficient data transfer while keeping the UI responsive.
Download PDF
Download EPUB
.epub digital book format is ideal for reading ebooks on phones, tablets, and e-readers.