23,99 €
Take your application to the next level of high performance using the extensive capabilities of Node.js
About This Book
Analyze, benchmark, and profile your Node.js application to find slow spots, and push it to the limit by eliminating performance bottlenecks
Learn the basis of performance analysis using Node.js
Explore the high performance capabilities of Node.js, along with best practices
In Detail
Node.js is a tool written in C, which allows you to use JavaScript on the server-side. High performance on a platform like Node.js is knowing how to take advantage of every aspect of your hardware, helping memory management act at its best, and correctly deciding how to architect a complex application. Do not panic if your applications start consuming a lot of memory; instead spot the leak and solve it fast with Node.js by monitoring and stopping it before it becomes an issue.
This book will provide you with the skills you need to analyze the performance of your application and monitor the aspects that can and should be. Starting with performance analysis concepts and their importance in helping Node.js developers eliminate performance bottlenecks, this book will take you through development patterns to avoid performance penalties. You will learn the importance of garbage collection and its behaviour,and discover how to profile your processor, allowing better performance and scalability.
You will then learn about the different types of data storage methods. Moving on, you will get to grips with testing and benchmarking applications to avoid unknown application test zones. Lastly, you will explore the limits that external components can impose in your application in the form of bottlenecks.
By following the examples in each chapter, you will discover tips to getting better performing applications by avoiding anti-patterns and stretching the limits of your environment as much as possible.
What You Will Learn
Develop applications using well-defined and well-tested development patterns
Explore memory management and garbage collection to improve performance
Monitor memory changes and analyze heap snapshots
Profile the CPU and improve your code to avoid patterns that force intensive processor usage
Understand the importance of data and when you should cache information
Learn to always test your code and benchmark when needed
Extend your application’s scope and know what other elements can influence performance
Who This Book Is For
This book is for Node.js developers who want a more in-depth knowledge of the platform to improve the performance of their applications. Whether you have a base Node.js background or you are an expert who knows the garbage collector and wants to leverage it to make applications more robust, the examples in this book will benefit you.
Style and approach
This is a practical guide to learning high performance, which even the least experienced developer will comprehend. Small and simple examples help you test concepts yourself and easily adapt them to any application, boosting its performance and preparing it for the real-world.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 178
Veröffentlichungsjahr: 2015
Copyright © 2015 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: August 2015
Production reference: 1120815
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78528-614-8
www.packtpub.com
Author
Diogo Resende
Reviewers
Abhishek Dey
Glenn Geenen
Stefan Lapers
Aravind V.S
Commissioning Editor
Ashwin Nair
Acquisition Editor
Sonali Vernekar
Content Development Editor
Rashmi Suvarna
Technical Editor
Utkarsha S. Kadam
Copy Editor
Vikrant Phadkay
Project Coordinator
Judie Jose
Proofreader
Safis Editing
Indexer
Rekha Nair
Production Coordinator
Manu Joseph
Cover Work
Manu Joseph
Diogo Resende is a passionate developer obsessed with perfection in everything he works on. He loves everything about the Internet of Things, which is the ability to connect everything together and always be connected to the world.
He studied computer science and graduated in engineering. At that time, he deepened his knowledge of computer networking and security, software development, and cloud computing. Over the past 10 years, Diogo has embraced different challenges to develop applications and services to connect people with embedded devices around the world, building a bridge between old and uncommon protocols and the Internet of today.
ThinkDigital has been his employer and a major part of his life for the last few years. It offers services and expertise in areas such as computer networking and security, automation, smart metering, and fleet management and intelligence. Diogo has also published many open source projects. You can find them all, with an MIT license style, on his personal GitHub page under the username dresende.
First of all, I would like to thank my wife, Ana, for putting up with my late-night writing sessions. She has given me enough of the space and tranquility that I needed to take up this challenge. I would also like to thank my son, Manuel, for being born exactly when I started writing the book, for stealing my attention but also making my days happier, and for giving me the strength to carry on and overcome every obstacle.
Last but not least, I would like to thank everyone in my company for putting up with me. I thank my business associate, Nuno, and my work colleagues Sílvia, Luis, and Helder for collaborating and helping the company go ahead and achieve all our dreams.
Abhishek Dey was born in Bandel, West Bengal, India. He holds an MS degree in computer engineering from the University of Florida, Gainesville, USA. His research interests lie primarily in the fields of compiler design, computer security, networks, data mining, analyses of algorithms, and concurrency and parallelism. He is a passionate programmer, who started programming in C and Java at the age of 10. Shortly afterwards, he developed a strong interest in web technologies and system implementation.
Abhishek possesses profound expertise in developing high-volume software using C++, Java, C#, JavaScript, jQuery, AngularJS, and HTML5. He also enjoys coding in functional programming languages, such as SML. Some of his recent projects can be found at https://github.com/deyabhishek.
He is a Microsoft Certified Professional, an Oracle Certified Java Programmer, an Oracle Certified Professional Java EE Web Component Developer, and an Oracle Certified Professional Java EE Business Component Developer.
In his leisure time, Abhishek loves to listen to music, travel to interesting places, and paint something on canvas, giving colors to his imagination. More information about him can be found at http://abhishekdey.com.
He has reviewed Kali Linux CTF Blueprints, AngularJS UI Development, RESTful Web API Design with Node.js, and Mastering AngularJS for .NET Developers, all by Packt Publishing.
Glenn Geenen is a Node.js developer with a background in game and mobile development. He worked mostly as an iOS consultant before becoming a Node.js consultant for his own company, GeenenTijd.
Stefan Lapers started his career almost 20 years ago as an IT support engineer. Then, he quickly grew in the field of Linux/Unix system engineering and software development.
Over the years, he has gained experience in deploying and maintaining hosted application solutions while working for prominent customers, such as MTV, TMF, and many more. In recent years, Stefan was involved in multiple development projects and their delivery as services on the Internet.
In his spare time, he enjoys being with his family and flying remotely controlled helicopters.
Aravind V.S is an aspiring mind and a creative brain to look forward to in the field of technology. He is a successful entrepreneur, developer, and technology consultant whose interest in embedded systems and computers paved his way into the programming world at the age of 15. At that time, he developed a full-fledged stock and inventory management system for a family friend. He has cofounded Entity Business Foundations, a web and mobile technology start-up based in Kerala (https://teamebf.com/); founded ioStash, an open source Internet of Things platform (http://iostash.com/); and tailored cloud:VAR, an open source backendless web application framework (http://cloudvar.org/) written in NodeJS and MongoDB.
In his spare time, Aravind can be found outdoors, focusing his camera, reading books, or writing articles for his blog at http://aravindvs.com/blog/. He has previously reviewed NodeJS Cookbook and NodeJS Essentials by Packt Publishing. Currently, he works as the chief technology officer at Entity Business Foundations. You can contact him at <[email protected]>.
I would like to take this opportunity to thank my friends—Harikrishnan, Abdulla Ahsan, and Muhammed Anas—and my parents for their support in completing the review of this book. Thanks especially to my best friend, Kavya Babu, for her enduring support, encouragement, and faith in me, without which I wouldn't have been what I am today. Above all, I'd like to thank the Almighty for giving me everything I needed at the right time.
For support files and downloads related to your book, please visit www.PacktPub.com.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.
If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.
High performance on a platform such as Node.js means knowing how to take advantage of every aspect of your hardware and helping memory management act at its best and correctly decide how to architect a complex application. Do not panic if your application starts consuming a lot of memory. Instead, spot the leak and solve it fast. Better yet, monitor and stop it before it becomes an issue.
Chapter 1, Introduction and Composition, introduces the subject, emphasizing performance analysis and the importance of benchmarking. It's about splitting applications into several smaller components, reducing the complexity of each component to a manageable level for the developers involved in the application. Here, you understand the importance of developing methodologies to break complexity into smaller and reusable modules that can more easily be analyzed and exchanged with other new and better modules during the course of the application's life cycle.
Chapter 2, Development Patterns, is about good programming patterns that help avoid performance penalties or help find them. You'll value the importance of carefully choosing techniques and patterns that are simple, and avoid future problems. With this in mind, you'll better understand how the language works, the importance of knowing the event loop, how asynchronous programming works best, and some of the first-class citizens of the language—streams and buffers.
Chapter 3, Garbage Collection, covers GC, its importance, and its behavior. Here, you get to understand V8 memory management, dead memory, and memory leaks. You also learn how to profile an application and spot memory leaks caused by bad programming where a developer hasn't deferenced objects correctly.
Chapter 4, CPU Profiling, is about profiling the processor and understanding when and why your application hogs your host. In this chapter, you understand the limits of the language and how to develop applications that can be divided into several components running across different hosts, allowing better performance and scalability.
Chapter 5, Data and Cache, explains externally stored application data and how it can affect your application's performance. It's about data stored locally in the application, the disk, a local service, a local network service or even the client host. In this chapter, you get to know that different types of data storage methods have different penalties, and these must be considered when choosing the best one. You learn that data can be stored locally or remotely and access to the data can be—and should be—cached sometimes, depending on the importance of the data.
Chapter 6, Test, Benchmark, and Analyze, is about testing and benchmarking applications. It's also about enforcing code coverage to avoid unknown application test zones. Then we cover benchmarks and benchmark analytics. You get to understand how good tests can pinpoint where to benchmark and analyze specific parts of the application to allow performance improvements.
Chapter 7, Bottlenecks, covers limits outside the application. This chapter is about the situations when you realize that the performance limit is not because of the application programing but external factors, such as the host hardware, network or client. You'll become aware of the limits that external components can impose on the application, locally or remotely. Moreover, the chapter explains that sometimes, the limits are on the client side and nothing can be done to improve the current performance.
The only software needed is Node.js. Some modules might need compilation, so a Linux or OS X operating system is easier for testing of the examples. No specific hardware is needed.
The book is intended for those with a basic Node.js background and those in need of a more in-depth understanding of this platform. Maybe, you're comfortable with the language and perhaps you know that it has a garbage collector, but you never really understand how it works and how it fails to work depending on the way you use the language. Basic language understanding and solid experience are required.
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "We can include other contexts through the use of the include directive."
A block of code is set as follows:
Any command-line input or output is written as follows:
New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Now, instead of choosing Take Snapshot, just click on the Load button and choose the snapshots from your disk."
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/6148OS.pdf.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <[email protected]> with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.
High performance is hard, and it depends on many factors. Best performance should be a constant goal for developers. To achieve it, a developer must know the programming language they use and, more importantly, how the language performs under heavy loads, these being disk, memory, network, and processor usage.
Developers will make the most out of a language if they know its weaknesses. In a perfect world, since every job is different, a developer should look for the best tool for the job. But this is not feasible and a developer wouldn't be able to know every best tool, so they have to look for the second best tool for every job. A developer will excel if they know few tools but master them.
As a metaphor, a hammer is used to drive nails, and you can also use it to break objects apart or forge metals, but you shouldn't use it to drive screws. The same applies to languages and platforms. Some platforms are very good for a lot of jobs but perform really badly at other jobs. This performance can sometimes be mitigated, but at other times, can't be avoided and you should look for better tools.
Node.js is not a language; it's actually a platform built on top of V8, Google's open source JavaScript engine. This engine implements ECMAScript, which itself is a simple and very flexible language. I say "simple" because it has no way of accessing the network, accessing the disk, or talking to other processes. It can't even stop execution since it has no kind of exit instruction. This language needs some kind of interface model on top of it to be useful. Node.js does this by exposing a (preferably) nonblocking I/O model using libuv. This nonblocking API allows you to access the filesystem, connect to network services and execute child processes.
The API also has two other important elements: buffers and streams. Since JavaScript strings are Unicode friendly, buffers were introduced to help deal with binary data. Streams are used as simple event interfaces to pass data around. Buffers and streams are used all over the API when reading file contents or receiving network packets.
A stream is a module, similar to the network module. When loaded, it provides access to some base classes that help create readable, writable, duplex, and transform streams. These can be used to perform all sorts of data manipulation in a simplified and unified format.
The buffers module easily becomes your best friend when converting binary data formats to some other format, for example, JSON. Multiple read and write methods help you convert integers and floats, signed or not, big endian or little endian, from 8 bits to 8 bytes long.
Most of the platform is designed to be simple, small, and stable. It's designed and ready to create some high-performance applications.
Performance is the amount of work completed in a defined period of time and with a set of defined resources. It can be analyzed using one or more metrics that depend on the performance goal. The goal can be low latency, low memory footprint, reduced processor usage, or even reduced power consumption.
The act of performance analysis is also called profiling. Profiling is very important for making optimized applications and is achieved by instrumenting either the source or the instance of the application. By instrumenting the source, developers can spot common performance weak spots. By instrumenting an application instance, they can test the application on different environments. This type of instrumentation can also be known by the name benchmarking.
Node.js is known for being fast. Actually, it's not that fast; it's just as fast as your resources allow it. What Node.js is best at is not blocking your application because of an I/O task. The perception of performance can be misleading in Node.js applications. In some other languages, when an application task gets blocked—for example, by a disk operation—all other tasks can be affected. In the case of Node.js, this doesn't happen—usually.