SlideShare a Scribd company logo
1 of 91
Ricky Bobby’s world
A look into the js performance
We’re speed freaks
[dahl]
Perf Paranoia
for loop vs foreach search
13,317,048
4,336,225
for loop vs foreach search
13,317,048
4,336,225
for loop vs foreach search
13,317,048
4,336,225
Speed Maintainability
var result = [];
for(var i=0, len=arr.length; i < len; i++) {
result.push(doSomething(arr[i]));
}
return result;
For loops are faster!
arr.map(doSomething);
MyFramework.CSS
MyFramework.Animations
MyFramework.Http
MyFramework.Socket
PROPERTY LOOKUPS
"Nesting objects in order to use dot notation is a great way to namespace and organize your code. Unfortunately, w
http://www.phpied.com/extreme-javascript-optimization/
MyFramework.Rendering.CSS
MyFramework.Rendering.Animations
MyFramework.Network.Http
MyFramework.Network.Socket
var Fn1 = 0;
var Fn2 = 1;
function nextFibonacci() {
var f1 = Fn1,
f2 = Fn2,
f3 = f1 + f2;
Fn1 = f2;
Fn2 = f3;
return f3;
}
Global Variable Caching
var Fn1 = 0;
var Fn2 = 1;
function nextFibonacci() {
var ret = Fn1 + Fn2;
Fn1 = Fn2;
Fn2 = ret;
return ret;
}
var iterations = Math.floor(values.length / 8);
var leftover = values.length % 8;
var i = 0;
if (leftover > 0){
do {
process(values[i++]);
} while (--leftover > 0);
}
do {
process(values[i++]);
process(values[i++]);
process(values[i++]);
process(values[i++]);
process(values[i++]);
process(values[i++]);
process(values[i++]);
process(values[i++]);
} while (--iterations > 0);
Loop unrolling
values.forEach(processData)
This is a tiny town…
”you are not allowed to care about the performance of * unless you
concatenate all your javascript, have it at the bottom, minify your css and
js, gzip all your assets, and losslessly compress all your images. If you
aren’t getting 90+ Page Speed scores, it’s way too early to be thinking
about selector optimization.”
Angels in the outfield
JavaScript is a single threaded,
interpreted language
Meanwhile…
Enter the declarative
var result = [];
for(var i=0, len=users.length; i < len; i++) {
if(users[i].name.length > 0) {
result.push(users[i]);
}
}
return result;
users.filter(function(u){
return u.name.length > 0
})
declarative
imperative
59 // src :: FlickrItem -> URL
60 var src = compose(_.get('m'), _.get('media'));
61
62 // srcs :: FlickrSearch -> [URL]
63 var srcs = compose(map(src), _.get('items'));
64
65 // images :: FlickrSearch -> [DOM]
66 var images = compose(map(imageTag), srcs);
67
68 // tags :: FlickrSearch -> [DOM]
69 var tags = compose(toP, _.countBy(_.identity), _.filter(_.isEmpty), chain(split(' '
70
71 // imagesAndTags :: Tuple [DOM] [DOM]
72 var imagesAndTags = liftA2(Tuple, images, tags)
73
74 // widget :: String -> PictureBox
75 var widget = compose(PictureBox, map(imagesAndTags), getJSON, url);
76
77 ///////////////////////////////////////////////////////////////////////////////////
78
79 mconcat([widget('cats'), widget('dogs')]).fork(log, function(x){
80 compose(setHtml($('#flickr')), _.first)(x)
81 compose(setHtml($(‘#tag_cloud')), _.last)(x)
82 });
83 });
PART 2
compose(map(g), map(f)) == map(compose(g, f))
chain(xs).map(f).map(g).value() == chain(xs).map(compose(g, f)).value()
Loop Fusion
Loop Fusion
var bigFirst = compose(map(first), map(capitalize))
var bigFirst = map(compose(first, capitalize))
bigFirst(['ham', 'cake']) // ['H', 'C']
Loop Fusion
var bigFirst = function(xs) {
return chain(xs).map(capitalize).map(first).value()
}
var bigFirst = function(xs) {
return chain(xs).map(compose(first, capitalize)).value()
}
bigFirst(['ham', 'cake']) // ['H', 'C']
It works for Functors and
Monads too!
Shortcut Fusion
// g :: forall b. (t -> b -> b) -> b -> b
reduce(c, n, build(g)) = g(c, n)
Shortcut Fusion
//build :: (forall b. (a -> b -> b) -> b -> b) -> [a]
var build = function(g){
return g(concat, []);
}
//+ map :: (a -> b) -> [a] -> [b]
var map = curry(function(f, xs){
return build(function(c, n){
return reduce(function(acc, x){ return c(f(x), acc); }, n, xs);
});
});
Shortcut Fusion
var sum = reduce(add, 0);
var sqr = function(x) {return x * x }
var sumSqs = compose(sum, map(sqr))
// reduce(function(acc, x){ return add(sqr(x), acc) }, 0);
Shortcut Fusion
var sum = reduce(add, 0);
var sqr = function(x) {return x * x }
var sumSqs = function(xs) {
return chain(xs).map(sqr).sum().value()
// chain(xs).reduce(function(acc, x){ return add(sqr(x), acc) }, 0).value();
}
Good Producers
• List comprehensions
• concat
• foldr
• map
• take
• filter
• partition
• head
• and, or, any, all
• sequence
• sortBy
• zip
• zipWith
• List comprehensions
• Explicit lists
• cons
• concat
• map
• take
• filter
• iterate, repeat
• repeat
• zip
• zipWith
Good Consumers
It works for Functors and
Monads too!
var addTwenty = memoize(function(x) {
return x + 20;
})
Memoization
var addTwenty = memoize(function(x) {
return x + 20;
})
addTwenty(10) // 30
addTwenty(10) // 30 (didn't run)
addTwenty(11) // 31
Memoization
Memoization
var getPosts = memoize(function(id) {
return new Future(function(rej, res) {
$.getJSON('/posts/'+id, res);
});
});
Memoization
var getPosts = memoize(function(id) {
return new Future(function(rej, res) {
$.getJSON('/posts/'+id, res);
});
});
getPosts(2) // Future
getPosts(2) // Future (didn't run)
getPosts(3) // Future
Memoization
var pQuery = $.toIO()
pQuery(".troll") // IO(function(){ return $(".troll") })
pQuery.runIO() // [Dom, Dom]
pQuery.runIO() // [Dom, Dom, Dom]
It works for Functors and
Monads too!
Parallel code
f(f(x, y), z) == f(x, f(y, z))
Parallel code
add(add(2, 3), 5) == add(2, add(3, 5))
Parallel code
add(2, 3, 5)
Parallel code
liftA3(fn, A1, A2, A3)
Parallel code
var longCalc // Int -> Future(Int)
var collectResults = curry(function(rslt1, rslt2, rslt3){})
liftA3(collectResults, longCalc(20), longCalc(30), longCalc(10))
Parallel code
var hasName // Attrs -> Validation
liftA3(save, hasName, hasEmail, hasPhone)
It works for Functors and
Monads too!
Compile while you
compose
var characters = [
{ 'name': 'barney', 'age': 36 },
{ 'name': 'fred', 'age': 40 },
{ 'name': 'pebbles', 'age': 1 }
];
var youngest = _.chain(characters)
.sortBy('age')
.map(function(chr) { return chr.name + ' is ' + chr.age; })
.first()
.value();
// → 'pebbles is 1’
Compile while you
compose
var characters = [
{ 'name': 'barney', 'age': 36 },
{ 'name': 'fred', 'age': 40 },
{ 'name': 'pebbles', 'age': 1 }
];
var youngest = _.chain(characters)
.sortBy('age')
.map(function(chr) { return chr.name + ' is ' + chr.age; })
.first()
.value();
// → 'pebbles is 1’
Lazy code
Lazy code
It works for Functors and
Monads too!
Just a handful
THANKS!
@drboolean

More Related Content

What's hot

HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6Dmitry Soshnikov
 
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011Masahiro Nagano
 
Building Real Time Systems on MongoDB Using the Oplog at Stripe
Building Real Time Systems on MongoDB Using the Oplog at StripeBuilding Real Time Systems on MongoDB Using the Oplog at Stripe
Building Real Time Systems on MongoDB Using the Oplog at StripeStripe
 
Building Real Time Systems on MongoDB Using the Oplog at Stripe
Building Real Time Systems on MongoDB Using the Oplog at StripeBuilding Real Time Systems on MongoDB Using the Oplog at Stripe
Building Real Time Systems on MongoDB Using the Oplog at StripeMongoDB
 
Introduction to cron queue
Introduction to cron queueIntroduction to cron queue
Introduction to cron queueADCI Solutions
 
Building Real Time Systems on MongoDB Using the Oplog at Stripe
Building Real Time Systems on MongoDB Using the Oplog at StripeBuilding Real Time Systems on MongoDB Using the Oplog at Stripe
Building Real Time Systems on MongoDB Using the Oplog at StripeMongoDB
 
EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is hereSebastiano Armeli
 
The Ring programming language version 1.5.2 book - Part 45 of 181
The Ring programming language version 1.5.2 book - Part 45 of 181The Ring programming language version 1.5.2 book - Part 45 of 181
The Ring programming language version 1.5.2 book - Part 45 of 181Mahmoud Samir Fayed
 
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)MongoSF
 
An Elephant of a Different Colour: Hack
An Elephant of a Different Colour: HackAn Elephant of a Different Colour: Hack
An Elephant of a Different Colour: HackVic Metcalfe
 
Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察Tsuyoshi Yamamoto
 
Coscup2021-rust-toturial
Coscup2021-rust-toturialCoscup2021-rust-toturial
Coscup2021-rust-toturialWayne Tsai
 
Зависимые типы в GHC 8. Максим Талдыкин
Зависимые типы в GHC 8. Максим ТалдыкинЗависимые типы в GHC 8. Максим Талдыкин
Зависимые типы в GHC 8. Максим ТалдыкинЮрий Сыровецкий
 
Groovy puzzlers jug-moscow-part 2
Groovy puzzlers jug-moscow-part 2Groovy puzzlers jug-moscow-part 2
Groovy puzzlers jug-moscow-part 2Evgeny Borisov
 
Javascript ES6 generators
Javascript ES6 generatorsJavascript ES6 generators
Javascript ES6 generatorsRamesh Nair
 

What's hot (20)

ES6 in Real Life
ES6 in Real LifeES6 in Real Life
ES6 in Real Life
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
 
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
 
Javascript
JavascriptJavascript
Javascript
 
Building Real Time Systems on MongoDB Using the Oplog at Stripe
Building Real Time Systems on MongoDB Using the Oplog at StripeBuilding Real Time Systems on MongoDB Using the Oplog at Stripe
Building Real Time Systems on MongoDB Using the Oplog at Stripe
 
Building Real Time Systems on MongoDB Using the Oplog at Stripe
Building Real Time Systems on MongoDB Using the Oplog at StripeBuilding Real Time Systems on MongoDB Using the Oplog at Stripe
Building Real Time Systems on MongoDB Using the Oplog at Stripe
 
Introduction to cron queue
Introduction to cron queueIntroduction to cron queue
Introduction to cron queue
 
Building Real Time Systems on MongoDB Using the Oplog at Stripe
Building Real Time Systems on MongoDB Using the Oplog at StripeBuilding Real Time Systems on MongoDB Using the Oplog at Stripe
Building Real Time Systems on MongoDB Using the Oplog at Stripe
 
EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is here
 
The Ring programming language version 1.5.2 book - Part 45 of 181
The Ring programming language version 1.5.2 book - Part 45 of 181The Ring programming language version 1.5.2 book - Part 45 of 181
The Ring programming language version 1.5.2 book - Part 45 of 181
 
はじめてのGroovy
はじめてのGroovyはじめてのGroovy
はじめてのGroovy
 
Rust ⇋ JavaScript
Rust ⇋ JavaScriptRust ⇋ JavaScript
Rust ⇋ JavaScript
 
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
 
An Elephant of a Different Colour: Hack
An Elephant of a Different Colour: HackAn Elephant of a Different Colour: Hack
An Elephant of a Different Colour: Hack
 
Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察
 
Coscup2021-rust-toturial
Coscup2021-rust-toturialCoscup2021-rust-toturial
Coscup2021-rust-toturial
 
Зависимые типы в GHC 8. Максим Талдыкин
Зависимые типы в GHC 8. Максим ТалдыкинЗависимые типы в GHC 8. Максим Талдыкин
Зависимые типы в GHC 8. Максим Талдыкин
 
ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
 
Groovy puzzlers jug-moscow-part 2
Groovy puzzlers jug-moscow-part 2Groovy puzzlers jug-moscow-part 2
Groovy puzzlers jug-moscow-part 2
 
Javascript ES6 generators
Javascript ES6 generatorsJavascript ES6 generators
Javascript ES6 generators
 

Viewers also liked

Functional Patterns for the non-mathematician
Functional Patterns for the non-mathematicianFunctional Patterns for the non-mathematician
Functional Patterns for the non-mathematicianBrian Lonsdorf
 
Functional Reactive Programming in Javascript
Functional Reactive Programming in JavascriptFunctional Reactive Programming in Javascript
Functional Reactive Programming in JavascriptBrian Lonsdorf
 

Viewers also liked (7)

Functional js class
Functional js classFunctional js class
Functional js class
 
Js for learning
Js for learningJs for learning
Js for learning
 
Liftin every day
Liftin every dayLiftin every day
Liftin every day
 
Millionways
MillionwaysMillionways
Millionways
 
Underscore
UnderscoreUnderscore
Underscore
 
Functional Patterns for the non-mathematician
Functional Patterns for the non-mathematicianFunctional Patterns for the non-mathematician
Functional Patterns for the non-mathematician
 
Functional Reactive Programming in Javascript
Functional Reactive Programming in JavascriptFunctional Reactive Programming in Javascript
Functional Reactive Programming in Javascript
 

Similar to Ricky Bobby’s guide to js performance

JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
How to build a html5 websites.v1
How to build a html5 websites.v1How to build a html5 websites.v1
How to build a html5 websites.v1Bitla Software
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 
Is HTML5 Ready? (workshop)
Is HTML5 Ready? (workshop)Is HTML5 Ready? (workshop)
Is HTML5 Ready? (workshop)Remy Sharp
 
Is html5-ready-workshop-110727181512-phpapp02
Is html5-ready-workshop-110727181512-phpapp02Is html5-ready-workshop-110727181512-phpapp02
Is html5-ready-workshop-110727181512-phpapp02PL dream
 
Chromium Embedded Framework + Go at Brooklyn JS
Chromium Embedded Framework + Go at Brooklyn JSChromium Embedded Framework + Go at Brooklyn JS
Chromium Embedded Framework + Go at Brooklyn JSquirkey
 
前端MVC之BackboneJS
前端MVC之BackboneJS前端MVC之BackboneJS
前端MVC之BackboneJSZhang Xiaoxue
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJSAaronius
 
Browsers with Wings
Browsers with WingsBrowsers with Wings
Browsers with WingsRemy Sharp
 
The State of JavaScript (2015)
The State of JavaScript (2015)The State of JavaScript (2015)
The State of JavaScript (2015)Domenic Denicola
 
SproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsSproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsMike Subelsky
 
Javascript Everywhere
Javascript EverywhereJavascript Everywhere
Javascript EverywherePascal Rettig
 
Phoenix + Reactで 社内システムを 密かに作ってる
Phoenix + Reactで 社内システムを 密かに作ってるPhoenix + Reactで 社内システムを 密かに作ってる
Phoenix + Reactで 社内システムを 密かに作ってるTakahiro Kobaru
 
Express Presentation
Express PresentationExpress Presentation
Express Presentationaaronheckmann
 
Cristiano Betta (Betta Works) - Lightweight Libraries with Rollup, Riot and R...
Cristiano Betta (Betta Works) - Lightweight Libraries with Rollup, Riot and R...Cristiano Betta (Betta Works) - Lightweight Libraries with Rollup, Riot and R...
Cristiano Betta (Betta Works) - Lightweight Libraries with Rollup, Riot and R...Techsylvania
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasminePaulo Ragonha
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptGuy Royse
 

Similar to Ricky Bobby’s guide to js performance (20)

JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
How to build a html5 websites.v1
How to build a html5 websites.v1How to build a html5 websites.v1
How to build a html5 websites.v1
 
Message in a bottle
Message in a bottleMessage in a bottle
Message in a bottle
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
Is HTML5 Ready? (workshop)
Is HTML5 Ready? (workshop)Is HTML5 Ready? (workshop)
Is HTML5 Ready? (workshop)
 
Is html5-ready-workshop-110727181512-phpapp02
Is html5-ready-workshop-110727181512-phpapp02Is html5-ready-workshop-110727181512-phpapp02
Is html5-ready-workshop-110727181512-phpapp02
 
Chromium Embedded Framework + Go at Brooklyn JS
Chromium Embedded Framework + Go at Brooklyn JSChromium Embedded Framework + Go at Brooklyn JS
Chromium Embedded Framework + Go at Brooklyn JS
 
前端MVC之BackboneJS
前端MVC之BackboneJS前端MVC之BackboneJS
前端MVC之BackboneJS
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJS
 
Browsers with Wings
Browsers with WingsBrowsers with Wings
Browsers with Wings
 
The State of JavaScript (2015)
The State of JavaScript (2015)The State of JavaScript (2015)
The State of JavaScript (2015)
 
SproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsSproutCore and the Future of Web Apps
SproutCore and the Future of Web Apps
 
Javascript Everywhere
Javascript EverywhereJavascript Everywhere
Javascript Everywhere
 
Intro to HTML5
Intro to HTML5Intro to HTML5
Intro to HTML5
 
Phoenix + Reactで 社内システムを 密かに作ってる
Phoenix + Reactで 社内システムを 密かに作ってるPhoenix + Reactで 社内システムを 密かに作ってる
Phoenix + Reactで 社内システムを 密かに作ってる
 
Spl Not A Bridge Too Far phpNW09
Spl Not A Bridge Too Far phpNW09Spl Not A Bridge Too Far phpNW09
Spl Not A Bridge Too Far phpNW09
 
Express Presentation
Express PresentationExpress Presentation
Express Presentation
 
Cristiano Betta (Betta Works) - Lightweight Libraries with Rollup, Riot and R...
Cristiano Betta (Betta Works) - Lightweight Libraries with Rollup, Riot and R...Cristiano Betta (Betta Works) - Lightweight Libraries with Rollup, Riot and R...
Cristiano Betta (Betta Works) - Lightweight Libraries with Rollup, Riot and R...
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
 

Recently uploaded

Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetEnjoy Anytime
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 

Recently uploaded (20)

Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 

Ricky Bobby’s guide to js performance

  • 1. Ricky Bobby’s world A look into the js performance
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 21.
  • 22.
  • 23.
  • 25.
  • 26.
  • 27.
  • 28. for loop vs foreach search 13,317,048 4,336,225
  • 29. for loop vs foreach search 13,317,048 4,336,225
  • 30. for loop vs foreach search 13,317,048 4,336,225
  • 31.
  • 32.
  • 33.
  • 35. var result = []; for(var i=0, len=arr.length; i < len; i++) { result.push(doSomething(arr[i])); } return result; For loops are faster! arr.map(doSomething);
  • 36. MyFramework.CSS MyFramework.Animations MyFramework.Http MyFramework.Socket PROPERTY LOOKUPS "Nesting objects in order to use dot notation is a great way to namespace and organize your code. Unfortunately, w http://www.phpied.com/extreme-javascript-optimization/ MyFramework.Rendering.CSS MyFramework.Rendering.Animations MyFramework.Network.Http MyFramework.Network.Socket
  • 37. var Fn1 = 0; var Fn2 = 1; function nextFibonacci() { var f1 = Fn1, f2 = Fn2, f3 = f1 + f2; Fn1 = f2; Fn2 = f3; return f3; } Global Variable Caching var Fn1 = 0; var Fn2 = 1; function nextFibonacci() { var ret = Fn1 + Fn2; Fn1 = Fn2; Fn2 = ret; return ret; }
  • 38. var iterations = Math.floor(values.length / 8); var leftover = values.length % 8; var i = 0; if (leftover > 0){ do { process(values[i++]); } while (--leftover > 0); } do { process(values[i++]); process(values[i++]); process(values[i++]); process(values[i++]); process(values[i++]); process(values[i++]); process(values[i++]); process(values[i++]); } while (--iterations > 0); Loop unrolling values.forEach(processData)
  • 39. This is a tiny town…
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45. ”you are not allowed to care about the performance of * unless you concatenate all your javascript, have it at the bottom, minify your css and js, gzip all your assets, and losslessly compress all your images. If you aren’t getting 90+ Page Speed scores, it’s way too early to be thinking about selector optimization.”
  • 46.
  • 47.
  • 48. Angels in the outfield
  • 49. JavaScript is a single threaded, interpreted language
  • 50.
  • 52.
  • 53.
  • 54.
  • 56.
  • 57. var result = []; for(var i=0, len=users.length; i < len; i++) { if(users[i].name.length > 0) { result.push(users[i]); } } return result; users.filter(function(u){ return u.name.length > 0 }) declarative imperative
  • 58. 59 // src :: FlickrItem -> URL 60 var src = compose(_.get('m'), _.get('media')); 61 62 // srcs :: FlickrSearch -> [URL] 63 var srcs = compose(map(src), _.get('items')); 64 65 // images :: FlickrSearch -> [DOM] 66 var images = compose(map(imageTag), srcs); 67 68 // tags :: FlickrSearch -> [DOM] 69 var tags = compose(toP, _.countBy(_.identity), _.filter(_.isEmpty), chain(split(' ' 70 71 // imagesAndTags :: Tuple [DOM] [DOM] 72 var imagesAndTags = liftA2(Tuple, images, tags) 73 74 // widget :: String -> PictureBox 75 var widget = compose(PictureBox, map(imagesAndTags), getJSON, url); 76 77 /////////////////////////////////////////////////////////////////////////////////// 78 79 mconcat([widget('cats'), widget('dogs')]).fork(log, function(x){ 80 compose(setHtml($('#flickr')), _.first)(x) 81 compose(setHtml($(‘#tag_cloud')), _.last)(x) 82 }); 83 });
  • 60. compose(map(g), map(f)) == map(compose(g, f)) chain(xs).map(f).map(g).value() == chain(xs).map(compose(g, f)).value() Loop Fusion
  • 61. Loop Fusion var bigFirst = compose(map(first), map(capitalize)) var bigFirst = map(compose(first, capitalize)) bigFirst(['ham', 'cake']) // ['H', 'C']
  • 62. Loop Fusion var bigFirst = function(xs) { return chain(xs).map(capitalize).map(first).value() } var bigFirst = function(xs) { return chain(xs).map(compose(first, capitalize)).value() } bigFirst(['ham', 'cake']) // ['H', 'C']
  • 63. It works for Functors and Monads too!
  • 64. Shortcut Fusion // g :: forall b. (t -> b -> b) -> b -> b reduce(c, n, build(g)) = g(c, n)
  • 65. Shortcut Fusion //build :: (forall b. (a -> b -> b) -> b -> b) -> [a] var build = function(g){ return g(concat, []); } //+ map :: (a -> b) -> [a] -> [b] var map = curry(function(f, xs){ return build(function(c, n){ return reduce(function(acc, x){ return c(f(x), acc); }, n, xs); }); });
  • 66. Shortcut Fusion var sum = reduce(add, 0); var sqr = function(x) {return x * x } var sumSqs = compose(sum, map(sqr)) // reduce(function(acc, x){ return add(sqr(x), acc) }, 0);
  • 67. Shortcut Fusion var sum = reduce(add, 0); var sqr = function(x) {return x * x } var sumSqs = function(xs) { return chain(xs).map(sqr).sum().value() // chain(xs).reduce(function(acc, x){ return add(sqr(x), acc) }, 0).value(); }
  • 68. Good Producers • List comprehensions • concat • foldr • map • take • filter • partition • head • and, or, any, all • sequence • sortBy • zip • zipWith • List comprehensions • Explicit lists • cons • concat • map • take • filter • iterate, repeat • repeat • zip • zipWith Good Consumers
  • 69. It works for Functors and Monads too!
  • 70. var addTwenty = memoize(function(x) { return x + 20; }) Memoization
  • 71. var addTwenty = memoize(function(x) { return x + 20; }) addTwenty(10) // 30 addTwenty(10) // 30 (didn't run) addTwenty(11) // 31 Memoization
  • 72. Memoization var getPosts = memoize(function(id) { return new Future(function(rej, res) { $.getJSON('/posts/'+id, res); }); });
  • 73. Memoization var getPosts = memoize(function(id) { return new Future(function(rej, res) { $.getJSON('/posts/'+id, res); }); }); getPosts(2) // Future getPosts(2) // Future (didn't run) getPosts(3) // Future
  • 74. Memoization var pQuery = $.toIO() pQuery(".troll") // IO(function(){ return $(".troll") }) pQuery.runIO() // [Dom, Dom] pQuery.runIO() // [Dom, Dom, Dom]
  • 75.
  • 76. It works for Functors and Monads too!
  • 77. Parallel code f(f(x, y), z) == f(x, f(y, z))
  • 78. Parallel code add(add(2, 3), 5) == add(2, add(3, 5))
  • 81. Parallel code var longCalc // Int -> Future(Int) var collectResults = curry(function(rslt1, rslt2, rslt3){}) liftA3(collectResults, longCalc(20), longCalc(30), longCalc(10))
  • 82. Parallel code var hasName // Attrs -> Validation liftA3(save, hasName, hasEmail, hasPhone)
  • 83. It works for Functors and Monads too!
  • 84. Compile while you compose var characters = [ { 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }, { 'name': 'pebbles', 'age': 1 } ]; var youngest = _.chain(characters) .sortBy('age') .map(function(chr) { return chr.name + ' is ' + chr.age; }) .first() .value(); // → 'pebbles is 1’
  • 85. Compile while you compose var characters = [ { 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }, { 'name': 'pebbles', 'age': 1 } ]; var youngest = _.chain(characters) .sortBy('age') .map(function(chr) { return chr.name + ' is ' + chr.age; }) .first() .value(); // → 'pebbles is 1’
  • 88. It works for Functors and Monads too!
  • 89.