0% found this document useful (0 votes)
3 views

TypeScript High Performance 1st Edition Ajinkya Kher pdf download

The document provides information about the book 'TypeScript High Performance' by Ajinkya Kher, which focuses on efficient strategies for handling asynchrony and optimizing resource delivery in TypeScript. It includes details about the author's background, the book's content, and its structure, covering various programming concepts and performance optimization techniques. Additionally, it offers links to other related books and resources for instant digital downloads.

Uploaded by

ifraimrafel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

TypeScript High Performance 1st Edition Ajinkya Kher pdf download

The document provides information about the book 'TypeScript High Performance' by Ajinkya Kher, which focuses on efficient strategies for handling asynchrony and optimizing resource delivery in TypeScript. It includes details about the author's background, the book's content, and its structure, covering various programming concepts and performance optimization techniques. Additionally, it offers links to other related books and resources for instant digital downloads.

Uploaded by

ifraimrafel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

TypeScript High Performance 1st Edition Ajinkya

Kher pdf download

https://ebookname.com/product/typescript-high-performance-1st-
edition-ajinkya-kher/

Get Instant Ebook Downloads – Browse at https://ebookname.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Nginx High Performance 1st Edition Rahul Sharma

https://ebookname.com/product/nginx-high-performance-1st-edition-
rahul-sharma/

High Performance Pigments 2nd Edition Faulkner

https://ebookname.com/product/high-performance-pigments-2nd-
edition-faulkner/

High Performance Loudspeakers Sixth Edition Martin


Colloms

https://ebookname.com/product/high-performance-loudspeakers-
sixth-edition-martin-colloms/

AASHTO LRFD Bridge Design Specifications Customary U S


Units with 2012 and 2013 Interim Revisions and 2012
Errata 6th Edition Edition Sam Zhang

https://ebookname.com/product/aashto-lrfd-bridge-design-
specifications-customary-u-s-units-with-2012-and-2013-interim-
revisions-and-2012-errata-6th-edition-edition-sam-zhang/
Rule of Two Star Wars Darth Bane Book 2 Drew Karpyshyn

https://ebookname.com/product/rule-of-two-star-wars-darth-bane-
book-2-drew-karpyshyn/

Cliffs AP English Language and Composition 2nd Edition


Barbara V. Swovelin

https://ebookname.com/product/cliffs-ap-english-language-and-
composition-2nd-edition-barbara-v-swovelin/

Fundamentals of engineering thermodynamics 5th Edition


Michael J. Moran

https://ebookname.com/product/fundamentals-of-engineering-
thermodynamics-5th-edition-michael-j-moran/

CareerJournal com Resume Guide for 100 000 Plus


Executive Jobs 1st Edition William E. Montag

https://ebookname.com/product/careerjournal-com-resume-guide-
for-100-000-plus-executive-jobs-1st-edition-william-e-montag/

Health Issues Injuries and Diseases 1st Edition Tsisana


Shartava

https://ebookname.com/product/health-issues-injuries-and-
diseases-1st-edition-tsisana-shartava/
Electric Power Distribution Reliability 1st Edition
Richard E. Brown

https://ebookname.com/product/electric-power-distribution-
reliability-1st-edition-richard-e-brown/
TypeScript High Performance

Learn efficient strategies for handling asynchrony and


optimizing resource delivery

Ajinkya Kher

BIRMINGHAM - MUMBAI
TypeScript High Performance
Copyright © 2017 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 2017

Production reference: 1210817


Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.

ISBN 978-1-78528-864-7

www.packtpub.com
Credits

Author Copy Editors


Ajinkya Kher Sameen Siddiqui
Pranjali Chury

Reviewer Project Coordinator


Andrew Macrae Vaidehi Sawant

Commissioning Editor Proofreader


Aaron Lazar Safis Editing

Acquisition Editor Indexer


Karan Sadawana Francy Puthiry

Content Development Editor Graphics


Zeeyan Pinheiro Abhinash Sahu

Technical Editor Production Coordinator


Vibhuti Gawde Nilesh Mohite
Foreword
Developing efficient software systems that meet the performance requirements and work
correctly as expected can be challenging without commitment from all layers of the
software development process. Adding more resources or patching things here and there on
an inefficiently written piece of software is often not enough and can greatly impact the
usability and usefulness of the system.

When performance is measured in microseconds, we can no longer rely on the hardware


performance improvements alone and need to optimize every aspect of the system, be it
selecting basic data structures or rendering critical resources. We need to understand and
make design decisions related to time-critical components and resources for improved
response time. Meanwhile, we cannot ignore testing the system for correctness and catching
bugs early on. I am delighted to see Ajinkya brings these perspectives to the readers in his
clearly written and well composed introduction to TypeScript for high efficiency and
performance. You are invited to think in terms of performance optimization and be
cognizant of the computational resources when building software systems. The book
provides clear examples related to efficient programming using TypeScript as well as
managing resources for responsive systems and user interfaces. Not only is the book
written in such a way that the reader can ramp up quickly to more advanced language
constructs, but they can also appreciate the rationale behind various choices for the given
use case. The practical examples meshed with empirical analysis of the performance for
each of the given design and implementation choices are quite refreshing and are scattered
throughout the book. Even novice readers can get the necessary insights and develop the
thought process for writing efficient and responsive software systems.

I am impressed by how much ground Ajinkya has covered in this book. Given his solid
background in full-stack software development, experience working with real-time
systems, and the desire to learn and grow along the way, the polished outcome in the form
of this book is not surprising. Ajinkya has truly brought his knowledge and insights to the
readers in an accessible manner and has let them in on the winning secrets that he has
leveraged in both professional settings and while triumphing in multiple Hackathons.

Maria Riaz, PhD

Software Engineer, Google Inc.


Over the last two decades, JavaScript has grown from enabling developers to perform
simple interactions with in-browser HTML to being the core of enterprise applications, both
frontend and backend. The success has become more apparent with the advent and creation
of NodeJS, Cordova, Ionic, and serverless frameworks, all of whom have adopted and
support TypeScript. This growth, coupled with the always increasing demand for complex
and performant JavaScript, has fueled the need for stricter typing, structures, and code
decoupling.

As a passionate technologist, fueled engineer, and creative problem solver, I have been a
witness and part of this evolution. I started using JavaScript in 2001 and have thoroughly
enjoyed the evolution since then. I enjoy the quirks of the language and the tiny things I’ve
spent hours trying to debug. I used to code in Notepad and would spend the proverbial 8
hours searching for a misspelled variable and massaging the bruises on my forehead from
the wall. I enjoy listening to everyone’s unique story about how they discovered that the
parseInt() function defines and documents two parameters, with the second being the radix
and probably the most frustrating parameter as it does not default to the expected value of
10.

We all have those unique yet similar stories. With TypeScript, we will save our children
from those headaches and hopefully reduce their chronic traumatic encephalopathy from
continuously beating their head against your basement wall. I have dabbled with
technologies on personal projects and I have worked for some of the biggest companies in
the world, including Microsoft, Siemens, Goldman Sachs, Deloitte, AT&T, and Coca-Cola.
With that experience, I hope that some of that can be shared with you as a reader of this
book.

If you are just beginning to venture into JavaScript or TypeScript, or if you’re a seasoned
veteran like me, you have something to gain from these pages. In my years of development
and consulting, I have never seen someone as passionate about learning tooling and
languages as Ajinkya. I worked with him when he first ventured into frontend development
with AngularJS.
The evolving world can be a scary place for most developers. This book has been designed
and is intended to allow you to smoothly transition from JavaScript to TypeScript, which is
why I highly recommend every JavaScript and TypeScript developer reads it cover to cover.
I recommend you read each section with an open mind and ask yourself questions or
consider reaching out to and engaging in forums, the publishing company, or industry
experts.

Congratulations on taking the first step toward the future of JavaScript, and smile while
you read this book!

Brian O’Connor

Solution Principal, Slalom Consulting


About the Author
Ajinkya Kher is a full stack developer, currently working at Microsoft on the
communications infrastructure for Skype and Microsoft teams. He is passionate about
modern scalable architectural patterns, efficient problem solving, and process design. His
experience and expertise is in the .NET middle tier/backend and modern HTML5 frontend
frameworks.

He loves getting his hands dirty with the latest and the greatest technologies out there. In
his free time, you can find him winning Hackathons, building mobile applications, and
lifting weights. He has been playing tennis for more than a decade and has been an ardent
fan of cricket and Sachin Tendulkar since childhood, his weekends are thus often spent
playing these two sports. He also likes to practice and read about spirituality and
philosophy whenever he can.

Check out his latest podcast Building Modern Web Applications using
React/Redux/Angular2/RxJs on YouTube and you can also follow him on LinkedIn.
Acknowlegement
I would like to express my gratitude to several people who have helped me through the
journey of this book. I would like to begin with my friends at Packt Publishing–-Sonali,
Kinnari, Vibhuti, and Zeeyan, who were of great help right from laying out the scope of the
book to offering comments, proofreading, and editing the chapters, all of which, I’m sure,
resulted in enhancing the quality of the book.

I would like to thank Brian and Maria for their generous contributions to this book. Both
Brian and Maria helped proofread the book and offered great feedback and encouragement.
I would like to specifically thank Brian for his invaluable contributions to Chapter 8, Build
and Development Strategies for Large-Scale Projects of this book.

I would like to thank Raji, who has constantly encouraged me to keep going and complete
this book. I would also like to thank my friends at work who encouraged me in the writing
process.

I would like to thank my family–-my mom, my dad, and my sister, Anushka, for their
invaluable and sincere feedback, encouragement, and most importantly, their patience
throughout the process. My parents were on a vacation here in Seattle as I was working
toward the completion of this book. They were very cheerful and supportive despite all the
time it took me away from them. This book wouldn’t have been complete without their
support.

Lastly, I would like to thank everyone who has helped shape me over the years and put me
in a position to share my insights and experience with you all in the form of this book.
About the Reviewer
Andrew Leith Macrae first cut his programming teeth on an Apple IIe, poking bytes into
the RAM. Over the years, he has developed interactive applications with Hypercard,
Director, Flash, and more recently, Adobe AIR for mobile. He has also worked with HTML
since there was HTML to work with and is currently working as a senior frontend
developer at The Learning Channel (www.tsc.ca), using Angular 4 with Typescript.

He is convinced that TypeScript is the future of JavaScript, bringing the structure and
discipline of strongly typed object-oriented language to facilitate efficient, intentional
coding for the development of large-scale applications for the Web.

You can find out more about Andrew or contact him at www.adventmedia.net.
www.PacktPub.com
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 service@packtpub.com 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://www.packtpub.com/mapt

Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt
books and video courses, as well as industry-leading tools to help you plan your personal
development and advance your career.

Why subscribe?
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Customer Feedback
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial
process. To help us improve, please leave us an honest review on this book's Amazon page
at https://www.amazon.com/dp/1785288644.

If you'd like to join our team of regular reviewers, you can e-mail us at
customerreviews@packtpub.com. We award our regular reviewers with free eBooks and
videos in exchange for their valuable feedback. Help us be relentless in improving our
products!
I dedicate this book to my mom, who is my first teacher, friend, and mentor. She taught me the
alphabet as a child, and she's still the first one to update me on the latest technological innovations.
She has dedicated her life towards my all-round growth and her contributions to my life are
incalculable.
Table of Contents
Preface 1
Chapter 1: Efficient Implementation of Basic Data Structures and
Algorithms 7
Strings 8
String concatenation 9
String replacement 12
Classes and interfaces 15
Loops and conditions 20
Arrays and sorting 26
Operators 30
Summary 33
Chapter 2: Variable Declarations, Namespaces, and Modules 34
Variable declarations 34
The var declarations 36
The let declarations 39
The const declarations 41
Namespaces and modules 41
Modules 45
Summary 48
Chapter 3: Efficient Usage of Advanced Language Constructs 49
Arrow functions 50
Mixins 55
Declaration merging 59
Triple-slash directives 64
Answers to declaration merging questions 67
Summary 71
Chapter 4: Asynchronous Programming and Responsive UI 72
Fundamentals of asynchronous programming and event loop 74
Synchronous data fetch 75
Asynchronous data fetch 76
Event loop 77
Callbacks 87
Callback Hell 93
Promises 95
Async and await 103
Summary 112
Chapter 5: Writing Quality Code 113
Unit tests 114
Static code analysis with TSLint 129
Setting up TSLint for your project 130
Editing default rules 136
Extending TSLint rules 138
TSLint VSCode Extension 139
Summary 142
Chapter 6: Efficient Resource Loading - Critical Rendering Path 143
Resource delivery across the internet 144
Optimizing the critical rendering path 148
Optimization 1 - render blocking CSS 152
Optimization 2 - render blocking JS 154
Non-blocking UI 157
Massive data downloads 157
Massive data uploads 161
Summary 162
Chapter 7: Profile Deployed JS with Developer Tools and Fiddler 163
Chrome Developer Tools 164
Memory profiling 164
Latency and computation time profiling 169
The Network tab 174
Fiddler 180
Summary 188
Chapter 8: Build and Deployment Strategies for Large-Scale Projects 189
Building locally 190
Grunt 190
Gulp 191
MSBuild 192
Continuous integration (CI) 193
The process 194
Jenkins 196
Bamboo 196
Continuous delivery (CD) 196
Chef 198

[]
Puppet 198
Containerization 198
Docker 199
Serverless applications 199
Testing 199
Summary 200
Index 201

[]
Preface
Over the last two decades, JavaScript has grown from enabling developers to perform
simple interactions with in-browser HTML to being the core of enterprise applications, both
frontend and backend. This success has become more apparent with the advent and
creations of NodeJS, Cordova, Ionic, and serverless frameworks, all of which have adopted
and support TypeScript. This growth, coupled with the ever-increasing demand for
complex and performant JavaScript, has fueled the need for stricter typing, structures, and
code decoupling.

TypeScript, created by Microsoft, is the long-awaited solution to these needed language


constructs. It is a superset of JavaScript, allowing for compilation to JavaScript and for
JavaScript to run within TypeScript. TypeScript is both open source and has backing from
major JavaScript libraries and frameworks, namely React, Angular, Express, Knockout, and
Ionic. This backing is evidence alone that TypeScript has garnered support from the cutting
edge in the industry.

With this evolution, it is necessary for learning to take place for newbies and gurus alike.
This book has been designed to walk through various topics of the language, building into
meaningful constructs to help you, as a TypeScript developer, build scalable, efficient, and
maintainable applications from the first line of code. We start by walking you through
language structure and terminology, continue through optimizing your code to load
quickly and fine-tune performance, and wrap up with a discussion on building and
deploying applications for large-scale and enterprise applications.

TypeScript is here to stay and will be looked back upon as the next iteration of JavaScript
just as its predecessors, such as Prototype, jQuery, Dojo, and Mootools, were. This book will
walk you through the language and will explain how to write efficient enterprise
TypeScript to scale.

What this book covers


This book has been assembled in topics that allow you to focus on your topics of interest.
Although we have tried to build self-contained chapters and sections, we highly
recommend reading each chapter thoroughly, as the latter sections in the book build on
material from the initial chapters.
Preface

Part I – Efficient usage of data structures,


language constructs, and handling asynchrony
Chapter 1, Efficient Implementation of Basic Data Structures and Algorithms, covers the efficient
implementation of basic TypeScript data structures, data types, and flow control with the
help of classic algorithms.

Chapter 2, Variable Declarations, Namespaces, and Modules, describes the distinction and
correct usage of variable declarations. It also describes code organization strategies, namely
leveraging namespaces and modules.

Chapter 3, Efficient Usage of Advanced Language Constructs, covers several different language
constructs in TypeScript. It explains how to use them, the scenarios in which to use each
construct, and their efficient usage.

Chapter 4, Asynchronous Programming and Responsive UI, is a deep dive into the world of
asynchronous programming. We walk you through the massive performance hits your
application can take if not built correctly, and we discuss strategies and tips for efficient
coding.

Part II – Performance monitoring, code quality,


and resource optimizations
Chapter 5, Writing Quality Code, covers the several configurations available with TSLint and
how they can be used to improve code quality and performance.

Chapter 6, Efficient Resource Loading - Critical Rendering Path, introduces the critical
rendering path and the steps involved in the process of loading a web application. We
discuss strategies for quick and non-blocking resource loading to produce a highly
responsive and performant application load.

Chapter 7, Profile Deployed JS with Developer Tools and Fiddler, introduces the concept of
profiling and the tools available. We compare the performance results of quality code
written with the help of TSLint and compare it to poorly written TypeScript code.

Part III – Building and deploying strategies for


large-scale TypeScript projects
Chapter 8, Building and Deploying Strategies for Large Scale Projects, covers the build and
deployment process of real-world, enterprise-scale TypeScript applications.

[2]
Preface

What you need for this book


The book requires the following things:

Node and NPM


TypeScript
Mocha Test Framework
Chai Assertion Library
Windows, Linux, or MacOS
Modern browsers--Chrome, Edge, and IE
Telerik Fiddler
Frontend editor--preferably VS Code or Atom/Sublime Text

Who this book is for


The scope of this book is broad, as are the applications and solutions that can be delivered
through TypeScript. As such, this book is essential for those who have a passion for
software at every stage of the life cycle, from ideation to architecture, design, build, and test.
This book should appeal to people who have embraced TypeScript for years and people
who have been in the JavaScript world and have debated making the jump to TypeScript.

Basic knowledge of TypeScript and some experience using JavaScript are prerequisites for
this book.

Conventions
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: "Since the
text variable was not previously defined, the log output will now display a compilation
error." A block of code is set as follows:
// const tests
function constTest(): () => number {
const x: number = 16;
x = 4; // Left-hand side of assignment expression cannot be
a constant
return function innerFunction(): number {
x++; // the operand of an increment or decrement operator

[3]
Preface

cannot be a constant
return x;
}
}

console.log('const test: ', constTest()());

When we wish to draw your attention to a particular part of a code block, the relevant lines
or items are set in bold:
[default]
exten => s,1,Dial(Zap/1|30)
exten => s,2,Voicemail(u100)
exten => s,102,Voicemail(b100)
exten => i,1,Voicemail(s0)

Any command-line input or output is written as follows:


ts-mocha test.ts

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: "Let's take a look at the
Network tab of the Developer Tools."

Warnings or important notes appear like this.

Tips and tricks appear like this.

Reader feedback
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
feedback@packtpub.com, 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.

[4]
Preface

Customer support
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.

Downloading the example code


You can download the example code files for this book from your account at
http://www.packtpub.com. 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.
You can download the code files by following these steps:

1. Log in or register to our website using your e-mail address and password.
2. Hover the mouse pointer on the SUPPORT tab at the top.
3. Click on Code Downloads & Errata.
4. Enter the name of the book in the Search box.
5. Select the book for which you're looking to download the code files.
6. Choose from the drop-down menu where you purchased this book from.
7. Click on Code Download.

Once the file is downloaded, please make sure that you unzip or extract the folder using the
latest version of:

WinRAR / 7-Zip for Windows


Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub


https://github.com/PacktPublishing/TypeScript-High-Performance. We also have
other code bundles from our rich catalog of books and videos available at
https://github.com/PacktPublishing/. Check them out!

[5]
Preface

Errata
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
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 copyright@packtpub.com with a link to the suspected pirated material. We
appreciate your help in protecting our authors and our ability to bring you valuable
content.

Questions
If you have a problem with any aspect of this book, you can contact us at
questions@packtpub.com, and we will do our best to address the problem.

[6]
Efficient Implementation of
1
Basic Data Structures and
Algorithms
One of the most important things to achieve optimal performance with any language is to
understand the correct usage of the data types and the constructs it offers. If leveraged
optimally, these features can help in producing a robust and high performance application,
but if leveraged in a non-optimal fashion, the same features can adversely impact the
overall performance and usability of the end product.

Let's take a look at the performance impact with the help of the following basic constructs,
operations, and data structures:

Strings: We will take a look at string concatenation and string replacement. We


will explore different ways of performing the same and understand the relative
merits of the different ways in terms of their performance impact.
Classes and interfaces: We will explore a famous design pattern with the help of
classes and interfaces and understand how a good design can help in achieving a
durable and scalable application.
Loops and conditions: We will look at the relative performances of the different
looping and conditional constructs the language offers.
Arrays and sorting: We will cover arrays by exploring a famous comparison-
based sorting algorithm and understand how the basics of optimizations can
greatly enhance the performance of an application.
Operators: We will take a look at the different operators that the language offers
and their basic usage.
Efficient Implementation of Basic Data Structures and Algorithms

Strings
Let's start by taking a look at strings. In TypeScript, you can create a string in one of the
following ways:
var test1: string = 'test string';

var test2: String = new String('test string');

For all practical purposes, you would almost always use the first way to work with strings.
The only difference between the two is that string is a literal type and a preferred way to
declare strings in TypeScript. String is an object type, which is essentially a wrapper object
around the string. From a performance standpoint, literal types tend to perform better than
object types. We can confirm this by running a simple code snippet as mentioned in the
following code snippet:
function createString_1(): string {
return `Lorem Ipsum is simply dummy text of the printing and
typesetting industry. Lorem Ipsum has been the industry''s
standard dummy text ever since the 1500s, when an unknown
printer took a galley of type and scrambled it to make a type
specimen book. It has survived not only five centuries, but also
the leap into electronic typesetting, remaining essentially
unchanged.It was popularised in the 1960s with the release of
Letraset sheets containing Lorem Ipsum passages, and more
recently with desktop publishing software like Aldus PageMaker
including versions of Lorem Ipsum.`;
}

function createString_2(): String {


return new String(`Lorem Ipsum is simply dummy text of the
printing and typesetting industry. Lorem Ipsum has been the
industry''s standard dummy text ever since the 1500s, when an
unknown printer took a galley of type and scrambled it to make a
type specimen book. It has survived not only five centuries, but
also the leap into electronic typesetting, remaining essentially
unchanged. It was popularised in the 1960s with the release of
Letraset sheets containing Lorem Ipsum passages, and more
recently with desktop publishing software like Aldus PageMaker
including versions of Lorem Ipsum.`);
}

// calculate time taken to create 50, 000 'strings'


let time1: number = Date.now();
for (let i = 0; i < 50000; i++) {
createString_1();
}

[8]
Efficient Implementation of Basic Data Structures and Algorithms

let time2: number = Date.now();


console.log('Time difference (createString_1): ', time2 - time1);

// calculate time taken to create 50, 000 'Strings'


time1 = Date.now();
for (let i = 0; i < 50000; i++) {
createString_2();
}

time2 = Date.now();
console.log('Time difference (createString_2): ', time2 - time1);

The preceding code snippet creates a long string (the famous filler text mostly used as a
placeholder on visual web elements) using the preceding described two ways.

The multiline string is represented in TypeScript by enclosing the string


within two back-tick/back-quote (`) characters. It's that easy!

Now, let's take a look at the results of executing the preceding code snippet:

Chrome (v56) IE (v11) Edge (v38)


createString_1() : string 3 ms 17 ms 13 ms
createString_2(): String 5 ms 42 ms 31 ms

Every set of time-based results mentioned in this book is an average of five


runs. For example, the average runtime of createString_1() on
Chrome (v56) across five runs is 3 milliseconds. We cover the runtime
across three browsers - Google Chrome version 56, Internet Explorer
Version 11, and Microsoft Edge Version 38.

As you can see from the results, the literal type string does behave slightly better. The
creation of the string, however, is not the most impacting operation that would affect your
application. Let's take a look at some classic string manipulation operations.

String concatenation
Let's start with string concatenation. Take a look at the following code snippet:
function createString(): string {
return `Lorem Ipsum is simply dummy text of the printing and
typesetting industry. Lorem Ipsum has been the industry''s

[9]
Another Random Document on
Scribd Without Any Related Topics
back
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookname.com

You might also like