SlideShare une entreprise Scribd logo
1  sur  52
Télécharger pour lire hors ligne
The new wave of
JavaScript techniques
Practical pairing of generative programming
with functional programming
Eugene Lazutkin, ClubAjax, 6/4/2013
Wednesday, June 5, 13
Generative programming
Wednesday, June 5, 13
What is GP?
Generative programming (GP):
Creates source code automatically to improve
programmer productivity.
Can be considered as a form of code reuse.
Sometimes called “automatic programming”.
Wednesday, June 5, 13
Examples of GP
Macro processors:
C preprocessor.
C++ templates and inline functions.
IDE “wizards” in Eclipse, MS Visual Studio.
Meta-languages and their compilers.
Domain-specific languages (DSL).
Wednesday, June 5, 13
Why do we need GP?
Higher-level programming.
Meta-programming.
Modeling.
DSL.
Wednesday, June 5, 13
Why do we need GP?
Performance improvements.
Program transformations.
Data transformations.
Code optimization and generation.
Applies to both compilers and interpreters.
Wednesday, June 5, 13
Why do I need GP?
Common narrative goes like that:
“Compilers and interpreters are now very
sophisticated – no need to optimize my code.”
“Modern CPUs with their fancy pipelining,
parallel execution, and branch prediction
eliminate code inefficiencies.”
Wednesday, June 5, 13
Don’t write inefficient code
Always estimate the algorithmic complexity of
your code (Big O notation).
Remember simple things:
Linear code usually works faster than code
with branches or loops.
Calling a function is not free. If its body is
small, it may make sense to inline it.
Wednesday, June 5, 13
Don’t write inefficient code
Remember simple things:
Simplify!
Simple shorter code is usually faster.
Eliminate unnecessary variables.
Profile!!!
BTW, this was an advice by Jared Jurkiewicz.
Wednesday, June 5, 13
Performance summary
Do not expect that an inefficient code will be
magically efficient. Always profile!
In a battle of a code clarity with a code
efficiency support the clarity, if possible.
Avoid premature optimization by taking complex
steps, yet do not write obviously slow code.
Wednesday, June 5, 13
JavaScript and GP
People coming from static languages frequently
overlook or discount GP facilities in JS.
JS has four ways to generate code dynamically:
eval(), new Function(), setTimeout(),
setInterval().
Browser allows to inline code.
Wednesday, June 5, 13
JavaScript and GP
Amazing code-generation facilities are a big
differentiator for Javascript.
Yet they are frequently shunned for numerous
reasons, including security, which is not applied
in all scenarios.
Wednesday, June 5, 13
JavaScript and GP
Recently GP crept in JavaScript libraries.
Examples:
Many templating languages are actually
compiled in JavaScript or can be compiled:
Mustache, Handlebars, jQuery templates...
Wednesday, June 5, 13
JavaScript and GP
Examples:
All JavaScript-based templates:
EJS, JST (e.g., Underscore, Lo-Dash)...
All transpilers:
CoffeeScript, GWT, Emscripten...
Numerous code-level tools (minifiers...).
Wednesday, June 5, 13
JavaScript and GP
Examples:
Some libraries generate code for similar
functions from the same template in order to
reduce their downloadable size, and optimize
performance.
Lo-Dash...
Wednesday, June 5, 13
Functional programming
Wednesday, June 5, 13
What is FP?
Functional programming (FP):
Treats computations as the evaluation of
mathematical functions.
Avoids state, mutations, side-effects.
Emphasizes “scenario” over “a list of actors”.
Concerns more with “how” rather than
“who” and “what”.
Wednesday, June 5, 13
JavaScript and FP
“JavaScript is Lisp in C’s clothing.” – said
Douglas Crockford back in 2001.
Functions are first-class objects.
Lambdas are supported (functions can be
inlined, and passed around).
Closures are supported (functions can access
their environment).
Wednesday, June 5, 13
Practical applications of FP
Abstracting control flow details with array extras:
var total = data
.filter(function(value){ return value % 2; })
.map(function(value){ return value * value; })
.reduce(function(acc, value){
return acc + value;
}, 0);
Wednesday, June 5, 13
Practical applications of FP
We can even use “building blocks” now:
var total = data
.filter(isOdd)
.map(square)
.reduce(sum, 0);
Wednesday, June 5, 13
Why I like this code
It is easy to understand.
It is easy to decompose or refactor.
There is no trivial technical noise like names of
index and value variables, and exit conditions.
Wednesday, June 5, 13
Building blocks
In general we are assumed to create our
programs from right-sized building blocks.
Bigger blocks are built from smaller blocks with a
mortar/language.
It applies to any programming paradigms.
Wednesday, June 5, 13
...and reality
How come in real projects we see methods and
functions in 100s and even 1000s lines of code?
Sometimes there are “good” reasons for that.
It can take more time to figure out our
building blocks than to code everything from
scratch.
Wednesday, June 5, 13
...and more reality
Sometimes there are “good” reasons for that.
Calling myriad of small functions can be
detrimental to performance.
Is it really the case? It can be verified with a
profiler, which takes time too.
It is possible to create a different system of
“building blocks”.
Wednesday, June 5, 13
Case for pipes
Pipes are individual components of a pipeline.
Each pipe has an input and an output
(sometimes more than one of those).
Pipeline combines individual pipes by
connecting their inputs and outputs producing a
program.
A pipeline can be used as a pipe.
Wednesday, June 5, 13
Case for pipes
Unix shells are a classic examples of pipes.
Closely related concept: dataflow.
Complex applications frequently can be
expressed in terms of event flow.
Hot topics in JS: event streams, data streams.
Wednesday, June 5, 13
Pipes and chaining
While chaining is a frequent implementation
technique for pipes, it doesn’t mean that all
chaining equates to pipes.
Pipes encapsulate streams of data and
orchestrate processing of individual bits.
Frequently chaining operates in terms of
transferred objects (streams), not data bits.
Wednesday, June 5, 13
Chaining
Examples in JS of chaining without piping:
jQuery
Underscore
JavaScript array extras
All examples above create a container object
before passing it down.
Wednesday, June 5, 13
Theory and practice
Wednesday, June 5, 13
Can we do better?
Let’s use our simple example as a start point and
optimize it by inlining functions:
var total = data
.filter(function(value){ return value % 2; })
.map(function(value){ return value * value; })
.reduce(function(acc, value){
return acc + value;
}, 0);
Wednesday, June 5, 13
Can we do better?
var a1 = [];
for(var i = 0; i < data.length; ++i){
if(data[i] % 2) a1.push(data[i]);
}
var a2 = new Array(a1.length);
for(var i = 0; i < a1.length; ++i){
a2[i] = a1[i] * a1[i];
}
var acc = 0;
for(var i = 0; i < a2.length; ++i){
acc += a2[i];
}
var total = acc;
Wednesday, June 5, 13
Can we do better?
Let’s merge loops and eliminate intermediate
arrays:
var acc = 0;
for(var i = 0; i < data.length; ++i){
var value = data[i];
if(value % 2) acc += value * value;
}
var total = acc;
Wednesday, June 5, 13
Performance results
0 750 1500 2250 3000
ms
Manual (38ms) Extra (2885ms)
Wednesday, June 5, 13
We did better!
And the results are in:
It is faster.
We loop over values manually.
We cannot easily move this snippet around
because our technical variable names may
clash.
Ultimately it was a trade-off.
Wednesday, June 5, 13
Can we have our cake and eat it too?
Yes!
Wednesday, June 5, 13
Can we have our cake and eat it too?
We need a way to describe a result.
Not how exactly get it, but its logical inference.
Then we can apply GP to generate an optimal
code.
Wednesday, June 5, 13
FP and pipes
FP gives us some answers:
Iterations can be described by higher-order
operations:
map, filter, fold/reduce, zipping, unzipping,
partitioning.
Secondary: forEach, every, some, indexOf.
Wednesday, June 5, 13
Heya Pipe
Wednesday, June 5, 13
Heya: ctr and pipe
Heya is a library that provides a modern
foundation for building web applications (both
server and client).
Heya Pipe is a functional toolkit to build efficient
data and event processing pipes using GP.
Heya Ctr provides a constructor to build
generated components.
Wednesday, June 5, 13
The Heya way
Let’s use our simple example and optimize it with
Heya Pipe:
var total = data
.filter(function(value){ return value % 2; })
.map(function(value){ return value * value; })
.reduce(function(acc, value){
return acc + value;
}, 0);
Wednesday, June 5, 13
The Heya way
Here it is:
var f = array(new Pipe()
.filter(“value % 2”)
.map(“value *= value;”)
.fold(“accumulator += value;”, 0)
).compile();
var total = f(data);
Wednesday, June 5, 13
Performance results
0 750 1500 2250 3000
ms
Manual (38ms) Pipe (53ms) Extra (2885ms)
Wednesday, June 5, 13
What do we see?
We are as expressive as array extras.
We are as performant as manual code.
The performance gap can be reduced.
In any case pipes are >40x faster than array
extras.
Wednesday, June 5, 13
Heya Pipe conventions
Heya Pipe is modeled after array extras.
It can accept the same parameters.
If a string is specified instead of a function it is
assumed to be a code snippet.
Code snippets work by conventions.
Wednesday, June 5, 13
Heya Pipe conventions
Snippets can have several lines of code.
“Boolean” snippets assume that the last line
returns a boolean value.
Snippet’s input is a “value” variable. A snippet
can modify it to return a different value.
Snippets for fold-able operations can access and
update an “accumulator” variable.
Wednesday, June 5, 13
Debugging
People make mistakes ⇒ code should be
debugged.
How to debug a generated code?
What is Heya Pipe story here?
Wednesday, June 5, 13
Debugging
The screenshot shows node.js debugging with
node-inspector.
The generated code appears in the file panel.
The code is fully readable.
Wednesday, June 5, 13
Heya Pipe
Provides a rich foundation for pipes:
forEach, transform, map, filter, indexOf, every,
some, fold, scan, skip, take, skipWhile,
takeWhile, voidResult.
Can work with potentially infinite streams.
Wednesday, June 5, 13
Heya Pipe
Can iterate over numerous containers:
Array (sparse and dense, including in reverse),
array slices (including in reverse), Object (keys,
values, own and inherited), iterators,
enumerators, generators, and perform unfold.
Includes a compiler, and an interpreter.
Can use pipes as sub-pipes.
Wednesday, June 5, 13
Heya Ctr
Implements GP helpers.
Includes a simple formatting-aware
templating.
Allows managing closures.
Serves as a foundation for Heya Pipes.
Wednesday, June 5, 13
Closures with Heya Ctr
Allows to inject variables in a closure, which will
be directly accessible from snippets by name.
Does not use “with” statement because it is
incompatible with strict mode.
Fully strict mode compatible.
Allows to access and modify closure-bound
variables.
Wednesday, June 5, 13
!at’s all
Folks!
Wednesday, June 5, 13

Contenu connexe

Tendances

Qtp realtime scripts
Qtp realtime scriptsQtp realtime scripts
Qtp realtime scripts
Ramu Palanki
 
Building High-Performance Language Implementations With Low Effort
Building High-Performance Language Implementations With Low EffortBuilding High-Performance Language Implementations With Low Effort
Building High-Performance Language Implementations With Low Effort
Stefan Marr
 

Tendances (20)

Skiron - Experiments in CPU Design in D
Skiron - Experiments in CPU Design in DSkiron - Experiments in CPU Design in D
Skiron - Experiments in CPU Design in D
 
clWrap: Nonsense free control of your GPU
clWrap: Nonsense free control of your GPUclWrap: Nonsense free control of your GPU
clWrap: Nonsense free control of your GPU
 
C++ Coroutines
C++ CoroutinesC++ Coroutines
C++ Coroutines
 
Best Practices in Qt Quick/QML - Part 3
Best Practices in Qt Quick/QML - Part 3Best Practices in Qt Quick/QML - Part 3
Best Practices in Qt Quick/QML - Part 3
 
Know yourengines velocity2011
Know yourengines velocity2011Know yourengines velocity2011
Know yourengines velocity2011
 
Optimizing Communicating Event-Loop Languages with Truffle
Optimizing Communicating Event-Loop Languages with TruffleOptimizing Communicating Event-Loop Languages with Truffle
Optimizing Communicating Event-Loop Languages with Truffle
 
Best Practices in Qt Quick/QML - Part 2
Best Practices in Qt Quick/QML - Part 2Best Practices in Qt Quick/QML - Part 2
Best Practices in Qt Quick/QML - Part 2
 
Big-data-analysis-training-in-mumbai
Big-data-analysis-training-in-mumbaiBig-data-analysis-training-in-mumbai
Big-data-analysis-training-in-mumbai
 
Qtp realtime scripts
Qtp realtime scriptsQtp realtime scripts
Qtp realtime scripts
 
A Domain-Specific Embedded Language for Programming Parallel Architectures.
A Domain-Specific Embedded Language for Programming Parallel Architectures.A Domain-Specific Embedded Language for Programming Parallel Architectures.
A Domain-Specific Embedded Language for Programming Parallel Architectures.
 
Building High-Performance Language Implementations With Low Effort
Building High-Performance Language Implementations With Low EffortBuilding High-Performance Language Implementations With Low Effort
Building High-Performance Language Implementations With Low Effort
 
Zero-Overhead Metaprogramming: Reflection and Metaobject Protocols Fast and w...
Zero-Overhead Metaprogramming: Reflection and Metaobject Protocols Fast and w...Zero-Overhead Metaprogramming: Reflection and Metaobject Protocols Fast and w...
Zero-Overhead Metaprogramming: Reflection and Metaobject Protocols Fast and w...
 
Best Practices in Qt Quick/QML - Part III
Best Practices in Qt Quick/QML - Part IIIBest Practices in Qt Quick/QML - Part III
Best Practices in Qt Quick/QML - Part III
 
Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...
 
Go Faster With Native Compilation
Go Faster With Native CompilationGo Faster With Native Compilation
Go Faster With Native Compilation
 
Дмитрий Копляров , Потокобезопасные сигналы в C++
Дмитрий Копляров , Потокобезопасные сигналы в C++Дмитрий Копляров , Потокобезопасные сигналы в C++
Дмитрий Копляров , Потокобезопасные сигналы в C++
 
Pune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCDPune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCD
 
Comparing different concurrency models on the JVM
Comparing different concurrency models on the JVMComparing different concurrency models on the JVM
Comparing different concurrency models on the JVM
 
System verilog assertions
System verilog assertionsSystem verilog assertions
System verilog assertions
 
How and why I turned my old Java projects into a first-class serverless compo...
How and why I turned my old Java projects into a first-class serverless compo...How and why I turned my old Java projects into a first-class serverless compo...
How and why I turned my old Java projects into a first-class serverless compo...
 

En vedette

Generative programming (mostly parser generation)
Generative programming (mostly parser generation)Generative programming (mostly parser generation)
Generative programming (mostly parser generation)
Ralf Laemmel
 
Practical Meta Programming
Practical Meta ProgrammingPractical Meta Programming
Practical Meta Programming
Reggie Meisler
 
Transformational-Generative Grammar
Transformational-Generative GrammarTransformational-Generative Grammar
Transformational-Generative Grammar
Ruth Ann Llego
 
Ubiquitous Computing
Ubiquitous ComputingUbiquitous Computing
Ubiquitous Computing
u065932
 

En vedette (16)

Dojo GFX: SVG in the real world
Dojo GFX: SVG in the real worldDojo GFX: SVG in the real world
Dojo GFX: SVG in the real world
 
Exciting JavaScript - Part II
Exciting JavaScript - Part IIExciting JavaScript - Part II
Exciting JavaScript - Part II
 
Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part I
 
Seeking Enligtenment - A journey of purpose rather tan instruction
Seeking Enligtenment - A journey of purpose rather tan instructionSeeking Enligtenment - A journey of purpose rather tan instruction
Seeking Enligtenment - A journey of purpose rather tan instruction
 
Generative programming (mostly parser generation)
Generative programming (mostly parser generation)Generative programming (mostly parser generation)
Generative programming (mostly parser generation)
 
Practical Meta Programming
Practical Meta ProgrammingPractical Meta Programming
Practical Meta Programming
 
Generative Software Development. Overview and Examples
Generative Software Development. Overview and ExamplesGenerative Software Development. Overview and Examples
Generative Software Development. Overview and Examples
 
A Generative Programming Approach to Developing Pervasive Computing Systems
A Generative Programming Approach to Developing Pervasive Computing SystemsA Generative Programming Approach to Developing Pervasive Computing Systems
A Generative Programming Approach to Developing Pervasive Computing Systems
 
Generative and Meta-Programming - Modern C++ Design for Parallel Computing
Generative and Meta-Programming - Modern C++ Design for Parallel ComputingGenerative and Meta-Programming - Modern C++ Design for Parallel Computing
Generative and Meta-Programming - Modern C++ Design for Parallel Computing
 
Japanese Open and Generative Design
Japanese Open and Generative DesignJapanese Open and Generative Design
Japanese Open and Generative Design
 
Seri Belajar Mandiri - Pemrograman C# Untuk Pemula
Seri Belajar Mandiri - Pemrograman C# Untuk PemulaSeri Belajar Mandiri - Pemrograman C# Untuk Pemula
Seri Belajar Mandiri - Pemrograman C# Untuk Pemula
 
Probabilistic programming
Probabilistic programmingProbabilistic programming
Probabilistic programming
 
Summary - Transformational-Generative Theory
Summary - Transformational-Generative TheorySummary - Transformational-Generative Theory
Summary - Transformational-Generative Theory
 
Transformational-Generative Grammar
Transformational-Generative GrammarTransformational-Generative Grammar
Transformational-Generative Grammar
 
Deep structure and surface structure
Deep structure and surface structureDeep structure and surface structure
Deep structure and surface structure
 
Ubiquitous Computing
Ubiquitous ComputingUbiquitous Computing
Ubiquitous Computing
 

Similaire à Practical pairing of generative programming with functional programming.

Questions On The Code And Core Module
Questions On The Code And Core ModuleQuestions On The Code And Core Module
Questions On The Code And Core Module
Katie Gulley
 
r,rstats,r language,r packages
r,rstats,r language,r packagesr,rstats,r language,r packages
r,rstats,r language,r packages
Ajay Ohri
 
Performance modeling and simulation for accumulo applications
Performance modeling and simulation for accumulo applicationsPerformance modeling and simulation for accumulo applications
Performance modeling and simulation for accumulo applications
Accumulo Summit
 
Data Science Challenge presentation given to the CinBITools Meetup Group
Data Science Challenge presentation given to the CinBITools Meetup GroupData Science Challenge presentation given to the CinBITools Meetup Group
Data Science Challenge presentation given to the CinBITools Meetup Group
Doug Needham
 
Exploring SharePoint with F#
Exploring SharePoint with F#Exploring SharePoint with F#
Exploring SharePoint with F#
Talbott Crowell
 
Icpc2010 bettenburg
Icpc2010 bettenburgIcpc2010 bettenburg
Icpc2010 bettenburg
SAIL_QU
 

Similaire à Practical pairing of generative programming with functional programming. (20)

Questions On The Code And Core Module
Questions On The Code And Core ModuleQuestions On The Code And Core Module
Questions On The Code And Core Module
 
Pattern: PMML for Cascading and Hadoop
Pattern: PMML for Cascading and HadoopPattern: PMML for Cascading and Hadoop
Pattern: PMML for Cascading and Hadoop
 
Art & music vs Google App Engine
Art & music vs Google App EngineArt & music vs Google App Engine
Art & music vs Google App Engine
 
Lambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter LawreyLambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter Lawrey
 
r,rstats,r language,r packages
r,rstats,r language,r packagesr,rstats,r language,r packages
r,rstats,r language,r packages
 
Pivotal Data Labs - Technology and Tools in our Data Scientist's Arsenal
Pivotal Data Labs - Technology and Tools in our Data Scientist's Arsenal Pivotal Data Labs - Technology and Tools in our Data Scientist's Arsenal
Pivotal Data Labs - Technology and Tools in our Data Scientist's Arsenal
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008
 
Performance modeling and simulation for accumulo applications
Performance modeling and simulation for accumulo applicationsPerformance modeling and simulation for accumulo applications
Performance modeling and simulation for accumulo applications
 
Cloudera Data Science Challenge
Cloudera Data Science ChallengeCloudera Data Science Challenge
Cloudera Data Science Challenge
 
Data Science Challenge presentation given to the CinBITools Meetup Group
Data Science Challenge presentation given to the CinBITools Meetup GroupData Science Challenge presentation given to the CinBITools Meetup Group
Data Science Challenge presentation given to the CinBITools Meetup Group
 
Lone StarPHP 2013 - Building Web Apps from a New Angle
Lone StarPHP 2013 - Building Web Apps from a New AngleLone StarPHP 2013 - Building Web Apps from a New Angle
Lone StarPHP 2013 - Building Web Apps from a New Angle
 
Elasticsearch's aggregations &amp; esctl in action or how i built a cli tool...
Elasticsearch's aggregations &amp; esctl in action  or how i built a cli tool...Elasticsearch's aggregations &amp; esctl in action  or how i built a cli tool...
Elasticsearch's aggregations &amp; esctl in action or how i built a cli tool...
 
Exploring SharePoint with F#
Exploring SharePoint with F#Exploring SharePoint with F#
Exploring SharePoint with F#
 
Easy R
Easy REasy R
Easy R
 
Google App Engine for Java
Google App Engine for JavaGoogle App Engine for Java
Google App Engine for Java
 
02 c++g3 d (1)
02 c++g3 d (1)02 c++g3 d (1)
02 c++g3 d (1)
 
Scalding for Hadoop
Scalding for HadoopScalding for Hadoop
Scalding for Hadoop
 
10 things I’ve learnt In the clouds
10 things I’ve learnt In the clouds10 things I’ve learnt In the clouds
10 things I’ve learnt In the clouds
 
Research @ RELEASeD (presented at SATTOSE2013)
Research @ RELEASeD (presented at SATTOSE2013)Research @ RELEASeD (presented at SATTOSE2013)
Research @ RELEASeD (presented at SATTOSE2013)
 
Icpc2010 bettenburg
Icpc2010 bettenburgIcpc2010 bettenburg
Icpc2010 bettenburg
 

Plus de Eugene Lazutkin

Plus de Eugene Lazutkin (16)

Service workers
Service workersService workers
Service workers
 
Advanced I/O in browser
Advanced I/O in browserAdvanced I/O in browser
Advanced I/O in browser
 
Functional practices in JavaScript
Functional practices in JavaScriptFunctional practices in JavaScript
Functional practices in JavaScript
 
Express: the web server for node.js
Express: the web server for node.jsExpress: the web server for node.js
Express: the web server for node.js
 
TXJS 2013 in 10 minutes
TXJS 2013 in 10 minutesTXJS 2013 in 10 minutes
TXJS 2013 in 10 minutes
 
Optimization of modern web applications
Optimization of modern web applicationsOptimization of modern web applications
Optimization of modern web applications
 
OOP in JS
OOP in JSOOP in JS
OOP in JS
 
Pulsar
PulsarPulsar
Pulsar
 
SSJS, NoSQL, GAE and AppengineJS
SSJS, NoSQL, GAE and AppengineJSSSJS, NoSQL, GAE and AppengineJS
SSJS, NoSQL, GAE and AppengineJS
 
Dojo for programmers (TXJS 2010)
Dojo for programmers (TXJS 2010)Dojo for programmers (TXJS 2010)
Dojo for programmers (TXJS 2010)
 
RAD CRUD
RAD CRUDRAD CRUD
RAD CRUD
 
CRUD with Dojo
CRUD with DojoCRUD with Dojo
CRUD with Dojo
 
Dojo GFX workshop slides
Dojo GFX workshop slidesDojo GFX workshop slides
Dojo GFX workshop slides
 
Dojo (QCon 2007 Slides)
Dojo (QCon 2007 Slides)Dojo (QCon 2007 Slides)
Dojo (QCon 2007 Slides)
 
DojoX GFX Session Eugene Lazutkin SVG Open 2007
DojoX GFX Session Eugene Lazutkin SVG Open 2007DojoX GFX Session Eugene Lazutkin SVG Open 2007
DojoX GFX Session Eugene Lazutkin SVG Open 2007
 
DojoX GFX Keynote Eugene Lazutkin SVG Open 2007
DojoX GFX Keynote Eugene Lazutkin SVG Open 2007DojoX GFX Keynote Eugene Lazutkin SVG Open 2007
DojoX GFX Keynote Eugene Lazutkin SVG Open 2007
 

Dernier

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
Enterprise Knowledge
 

Dernier (20)

[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
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
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
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
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 

Practical pairing of generative programming with functional programming.

  • 1. The new wave of JavaScript techniques Practical pairing of generative programming with functional programming Eugene Lazutkin, ClubAjax, 6/4/2013 Wednesday, June 5, 13
  • 3. What is GP? Generative programming (GP): Creates source code automatically to improve programmer productivity. Can be considered as a form of code reuse. Sometimes called “automatic programming”. Wednesday, June 5, 13
  • 4. Examples of GP Macro processors: C preprocessor. C++ templates and inline functions. IDE “wizards” in Eclipse, MS Visual Studio. Meta-languages and their compilers. Domain-specific languages (DSL). Wednesday, June 5, 13
  • 5. Why do we need GP? Higher-level programming. Meta-programming. Modeling. DSL. Wednesday, June 5, 13
  • 6. Why do we need GP? Performance improvements. Program transformations. Data transformations. Code optimization and generation. Applies to both compilers and interpreters. Wednesday, June 5, 13
  • 7. Why do I need GP? Common narrative goes like that: “Compilers and interpreters are now very sophisticated – no need to optimize my code.” “Modern CPUs with their fancy pipelining, parallel execution, and branch prediction eliminate code inefficiencies.” Wednesday, June 5, 13
  • 8. Don’t write inefficient code Always estimate the algorithmic complexity of your code (Big O notation). Remember simple things: Linear code usually works faster than code with branches or loops. Calling a function is not free. If its body is small, it may make sense to inline it. Wednesday, June 5, 13
  • 9. Don’t write inefficient code Remember simple things: Simplify! Simple shorter code is usually faster. Eliminate unnecessary variables. Profile!!! BTW, this was an advice by Jared Jurkiewicz. Wednesday, June 5, 13
  • 10. Performance summary Do not expect that an inefficient code will be magically efficient. Always profile! In a battle of a code clarity with a code efficiency support the clarity, if possible. Avoid premature optimization by taking complex steps, yet do not write obviously slow code. Wednesday, June 5, 13
  • 11. JavaScript and GP People coming from static languages frequently overlook or discount GP facilities in JS. JS has four ways to generate code dynamically: eval(), new Function(), setTimeout(), setInterval(). Browser allows to inline code. Wednesday, June 5, 13
  • 12. JavaScript and GP Amazing code-generation facilities are a big differentiator for Javascript. Yet they are frequently shunned for numerous reasons, including security, which is not applied in all scenarios. Wednesday, June 5, 13
  • 13. JavaScript and GP Recently GP crept in JavaScript libraries. Examples: Many templating languages are actually compiled in JavaScript or can be compiled: Mustache, Handlebars, jQuery templates... Wednesday, June 5, 13
  • 14. JavaScript and GP Examples: All JavaScript-based templates: EJS, JST (e.g., Underscore, Lo-Dash)... All transpilers: CoffeeScript, GWT, Emscripten... Numerous code-level tools (minifiers...). Wednesday, June 5, 13
  • 15. JavaScript and GP Examples: Some libraries generate code for similar functions from the same template in order to reduce their downloadable size, and optimize performance. Lo-Dash... Wednesday, June 5, 13
  • 17. What is FP? Functional programming (FP): Treats computations as the evaluation of mathematical functions. Avoids state, mutations, side-effects. Emphasizes “scenario” over “a list of actors”. Concerns more with “how” rather than “who” and “what”. Wednesday, June 5, 13
  • 18. JavaScript and FP “JavaScript is Lisp in C’s clothing.” – said Douglas Crockford back in 2001. Functions are first-class objects. Lambdas are supported (functions can be inlined, and passed around). Closures are supported (functions can access their environment). Wednesday, June 5, 13
  • 19. Practical applications of FP Abstracting control flow details with array extras: var total = data .filter(function(value){ return value % 2; }) .map(function(value){ return value * value; }) .reduce(function(acc, value){ return acc + value; }, 0); Wednesday, June 5, 13
  • 20. Practical applications of FP We can even use “building blocks” now: var total = data .filter(isOdd) .map(square) .reduce(sum, 0); Wednesday, June 5, 13
  • 21. Why I like this code It is easy to understand. It is easy to decompose or refactor. There is no trivial technical noise like names of index and value variables, and exit conditions. Wednesday, June 5, 13
  • 22. Building blocks In general we are assumed to create our programs from right-sized building blocks. Bigger blocks are built from smaller blocks with a mortar/language. It applies to any programming paradigms. Wednesday, June 5, 13
  • 23. ...and reality How come in real projects we see methods and functions in 100s and even 1000s lines of code? Sometimes there are “good” reasons for that. It can take more time to figure out our building blocks than to code everything from scratch. Wednesday, June 5, 13
  • 24. ...and more reality Sometimes there are “good” reasons for that. Calling myriad of small functions can be detrimental to performance. Is it really the case? It can be verified with a profiler, which takes time too. It is possible to create a different system of “building blocks”. Wednesday, June 5, 13
  • 25. Case for pipes Pipes are individual components of a pipeline. Each pipe has an input and an output (sometimes more than one of those). Pipeline combines individual pipes by connecting their inputs and outputs producing a program. A pipeline can be used as a pipe. Wednesday, June 5, 13
  • 26. Case for pipes Unix shells are a classic examples of pipes. Closely related concept: dataflow. Complex applications frequently can be expressed in terms of event flow. Hot topics in JS: event streams, data streams. Wednesday, June 5, 13
  • 27. Pipes and chaining While chaining is a frequent implementation technique for pipes, it doesn’t mean that all chaining equates to pipes. Pipes encapsulate streams of data and orchestrate processing of individual bits. Frequently chaining operates in terms of transferred objects (streams), not data bits. Wednesday, June 5, 13
  • 28. Chaining Examples in JS of chaining without piping: jQuery Underscore JavaScript array extras All examples above create a container object before passing it down. Wednesday, June 5, 13
  • 30. Can we do better? Let’s use our simple example as a start point and optimize it by inlining functions: var total = data .filter(function(value){ return value % 2; }) .map(function(value){ return value * value; }) .reduce(function(acc, value){ return acc + value; }, 0); Wednesday, June 5, 13
  • 31. Can we do better? var a1 = []; for(var i = 0; i < data.length; ++i){ if(data[i] % 2) a1.push(data[i]); } var a2 = new Array(a1.length); for(var i = 0; i < a1.length; ++i){ a2[i] = a1[i] * a1[i]; } var acc = 0; for(var i = 0; i < a2.length; ++i){ acc += a2[i]; } var total = acc; Wednesday, June 5, 13
  • 32. Can we do better? Let’s merge loops and eliminate intermediate arrays: var acc = 0; for(var i = 0; i < data.length; ++i){ var value = data[i]; if(value % 2) acc += value * value; } var total = acc; Wednesday, June 5, 13
  • 33. Performance results 0 750 1500 2250 3000 ms Manual (38ms) Extra (2885ms) Wednesday, June 5, 13
  • 34. We did better! And the results are in: It is faster. We loop over values manually. We cannot easily move this snippet around because our technical variable names may clash. Ultimately it was a trade-off. Wednesday, June 5, 13
  • 35. Can we have our cake and eat it too? Yes! Wednesday, June 5, 13
  • 36. Can we have our cake and eat it too? We need a way to describe a result. Not how exactly get it, but its logical inference. Then we can apply GP to generate an optimal code. Wednesday, June 5, 13
  • 37. FP and pipes FP gives us some answers: Iterations can be described by higher-order operations: map, filter, fold/reduce, zipping, unzipping, partitioning. Secondary: forEach, every, some, indexOf. Wednesday, June 5, 13
  • 39. Heya: ctr and pipe Heya is a library that provides a modern foundation for building web applications (both server and client). Heya Pipe is a functional toolkit to build efficient data and event processing pipes using GP. Heya Ctr provides a constructor to build generated components. Wednesday, June 5, 13
  • 40. The Heya way Let’s use our simple example and optimize it with Heya Pipe: var total = data .filter(function(value){ return value % 2; }) .map(function(value){ return value * value; }) .reduce(function(acc, value){ return acc + value; }, 0); Wednesday, June 5, 13
  • 41. The Heya way Here it is: var f = array(new Pipe() .filter(“value % 2”) .map(“value *= value;”) .fold(“accumulator += value;”, 0) ).compile(); var total = f(data); Wednesday, June 5, 13
  • 42. Performance results 0 750 1500 2250 3000 ms Manual (38ms) Pipe (53ms) Extra (2885ms) Wednesday, June 5, 13
  • 43. What do we see? We are as expressive as array extras. We are as performant as manual code. The performance gap can be reduced. In any case pipes are >40x faster than array extras. Wednesday, June 5, 13
  • 44. Heya Pipe conventions Heya Pipe is modeled after array extras. It can accept the same parameters. If a string is specified instead of a function it is assumed to be a code snippet. Code snippets work by conventions. Wednesday, June 5, 13
  • 45. Heya Pipe conventions Snippets can have several lines of code. “Boolean” snippets assume that the last line returns a boolean value. Snippet’s input is a “value” variable. A snippet can modify it to return a different value. Snippets for fold-able operations can access and update an “accumulator” variable. Wednesday, June 5, 13
  • 46. Debugging People make mistakes ⇒ code should be debugged. How to debug a generated code? What is Heya Pipe story here? Wednesday, June 5, 13
  • 47. Debugging The screenshot shows node.js debugging with node-inspector. The generated code appears in the file panel. The code is fully readable. Wednesday, June 5, 13
  • 48. Heya Pipe Provides a rich foundation for pipes: forEach, transform, map, filter, indexOf, every, some, fold, scan, skip, take, skipWhile, takeWhile, voidResult. Can work with potentially infinite streams. Wednesday, June 5, 13
  • 49. Heya Pipe Can iterate over numerous containers: Array (sparse and dense, including in reverse), array slices (including in reverse), Object (keys, values, own and inherited), iterators, enumerators, generators, and perform unfold. Includes a compiler, and an interpreter. Can use pipes as sub-pipes. Wednesday, June 5, 13
  • 50. Heya Ctr Implements GP helpers. Includes a simple formatting-aware templating. Allows managing closures. Serves as a foundation for Heya Pipes. Wednesday, June 5, 13
  • 51. Closures with Heya Ctr Allows to inject variables in a closure, which will be directly accessible from snippets by name. Does not use “with” statement because it is incompatible with strict mode. Fully strict mode compatible. Allows to access and modify closure-bound variables. Wednesday, June 5, 13