SlideShare a Scribd company logo
1 of 43
The 73js
Let’s implement the 73 calculator
f(x) = {
3, x=7
7, x=3
¯_(ツ)_/¯, otherwise
}
Let’s implement the 73 calculator
f(x) = {
3, x=7
7, x=3
¯_(ツ)_/¯, otherwise
}
Use an if
static useif(n) {
if (n == 3) return 7;
return 3;
}
Use an if (the strict equality version)
static useifeq(n) {
if (n === 3) return 7;
return 3;
}
Use a Xor
static useXor(n) {
return (n ^= 4);
}
Use an array
static useArray(n) {
const mem = [-1,-1,-1,7,-1,-1,-1,3];
return mem[n];
}
The switch statement
static useSwitch(n) {
switch (n) {
case 7:
return 3;
case 3:
return 7;
default:
throw new exception("err");
}
}
useSubstraction
static useSubstraction(n) {
return 10 - n;
}
Division
static useDivision(n) {
return 21 / n;
}
String replace (I asked for a number)
static stringReplaceNumber(n) {
return Number("37".replace(n, ""));
}
String replace (I’ll parse you a number)
static stringReplaceParseInt(n) {
return parseInt("37".replace(n, ""));
}
Using modulo
static useModulo(n) {
return ((n + 4) % 8);
}
Using object map
static useObjectMap(n) {
const objmapper = {
3: 7,
7: 3
};
return objmapper[n];
}
Using indexer dictionary
static useIndexerDictionary(n) {
const dict = {};
dict[3] = 7;
dict[7] = 3;
return dict[n];
}
Using a Polynom
static usePolynom(n) {
return ((79 - (n * n)) / 10);
}
Let’s try another base
static useOctalCast(n) {
let numberAsOctal = (n + 4).toString(8)
return parseInt(numberAsOctal) % 10;
}
I bet there are a couple more
ways…
Using relational
databases, AI, routing,
statistics, fourier
transforms, various
functional bases, and the
sky is the limit…
There’s more than one way to skin
a cat
Now what?
Let’s find out which is best!
Using benchmark.js
var Benchmark = require('benchmark');
var suite = new Benchmark.Suite;
const The73Calculator = require("./The73Calculator.js");
suite.add(The73Calculator.useif.name, () => {
expectBehavior(The73Calculator.useif);
})
.add(The73Calculator.useifeq.name, () => {
expectBehavior(The73Calculator.useifeq);
})
.add(The73Calculator.useXor.name, () => {
expectBehavior(The73Calculator.useXor);
})
.add(The73Calculator.useArray.name, () => {
expectBehavior(The73Calculator.useArray);
})
.add(The73Calculator.usingSwitch.name, () => {
expectBehavior(The73Calculator.usingSwitch);
})
.add(The73Calculator.useSubstraction.name, () => {
expectBehavior(The73Calculator.useSubstraction);
})
.add(The73Calculator.useDivision.name, () => {
expectBehavior(The73Calculator.useDivision);
})
.add(The73Calculator.useStringReplaceParseInt.name, () => {
expectBehavior(The73Calculator.useStringReplaceParseInt);
// add listeners
.on('cycle', function(event) {
console.log(String(event.target));
})
.on('complete', function() {
report.sort((a, b) => (b.hz - a.hz));
report.forEach(r => console.log(r.name + " - " + r.hz));
console.log('Fastest is ' + this.filter('fastest').map('name'));
console.log('Slowest is ' + this.filter('slowest').map('name'));
})
// run async
.run({ 'async': true });
function expectBehavior(f) {
for (var i = 0; i < 100000; i++) {
f(3);
f(7);
}
}
If
Ifeq
Substraction
Division
Xor
Polynom
Modulo
Switch
Array
Octal
IndexerDictionary
StringReplaceNumber
StringReplaceParseInt
ObjectMap
And the winner is…
If
Ifeq
Substraction
Division
Xor
Polynom
Modulo
Switch
Array
Octal
IndexerDictionary
StringReplaceNumber
StringReplaceParseInt
ObjectMap
And the loser is…
If
Ifeq
Substraction
Division
Xor
Polynom
Modulo
Switch
Array
Octal
IndexerDictionary
StringReplaceNumber
StringReplaceParseInt
ObjectMap
To the results…
To the results……
javascript
Method runtime (us)
useif 24.52
useXor 827
useSubstraction 951
useifeq 956
usingSwitch 1012
useArray 1228
usingPolynom 1349
usingModulo 1547
division 1848
usingObjectMap 4950
octal 12938
usingIndexerDictionary 40371
stringReplaceNumber 48875
stringReplaceParseInt 64267
javascript c#
Method runtime (us) runtime (ns)
useif 24.52 485
useXor 827 437
useSubstraction 951 428
useifeq 956 498
usingSwitch 1012 501
useArray 1228 437
usingPolynom 1349 486
usingModulo 1547 432
division 1848 554
usingObjectMap 4950 4255
octal 12938 n/a
usingIndexerDictionary 40371 1335
stringReplaceNumber 48875 n/a
stringReplaceParseInt 64267 8474
You have to measure to know
If you haven’t measured, you don’t
know
If you think you know, and you
haven’t measured, you still don’t
know
Now what? (2 of n)
javascript c#
Method runtime (us) runtime (ns)
useif 24.52 485
useXor 827 437
useSubstraction 951 428
useifeq 956 498
usingSwitch 1012 501
useArray 1228 437
usingPolynom 1349 486
usingModulo 1547 432
division 1848 554
usingObjectMap 4950 4255
octal 12938 n/a
usingIndexerDictionary 40371 1335
stringReplaceNumber 48875 n/a
stringReplaceParseInt 64267 8474
javascript c#
Method runtime (us) runtime (ns)
useif 24.52 485
useXor 827 437
useSubstraction 951 428
useifeq 956 498
usingSwitch 1012 501
useArray 1228 437
usingPolynom 1349 486
usingModulo 1547 432
division 1848 554
usingObjectMap 4950 4255
octal 12938 n/a
usingIndexerDictionary 40371 1335
stringReplaceNumber 48875 n/a
stringReplaceParseInt 64267 8474
By that much?
This is
interesting #1
This is
interesting #2
You are a victim of branch
prediction fail.
Summary
There’s more than one way to skin
a cat
You have to measure to know
Benchmark.js is great
Energy awareness is a thing
@hanokhaloni
Hanokhaloni
hanokhaloni
https://github.com/hanokhaloni/73js

More Related Content

Similar to NWD the73js.pptx

Jscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScriptJscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScriptjeffz
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSAdam L Barrett
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming iiPrashant Kalkar
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jscacois
 
how to reuse code
how to reuse codehow to reuse code
how to reuse codejleed1
 
Javascript function
Javascript functionJavascript function
Javascript functionLearningTech
 
Javascript Uncommon Programming
Javascript Uncommon ProgrammingJavascript Uncommon Programming
Javascript Uncommon Programmingjeffz
 
Jarmo van de Seijp Shadbox ERC223
Jarmo van de Seijp Shadbox ERC223Jarmo van de Seijp Shadbox ERC223
Jarmo van de Seijp Shadbox ERC223Jarmo van de Seijp
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6Dmitry Soshnikov
 
Selective codes
Selective codesSelective codes
Selective codesSiva Gopal
 
Groovy grails types, operators, objects
Groovy grails types, operators, objectsGroovy grails types, operators, objects
Groovy grails types, operators, objectsHusain Dalal
 

Similar to NWD the73js.pptx (20)

Javascript
JavascriptJavascript
Javascript
 
Seminar PSU 10.10.2014 mme
Seminar PSU 10.10.2014 mmeSeminar PSU 10.10.2014 mme
Seminar PSU 10.10.2014 mme
 
Millionways
MillionwaysMillionways
Millionways
 
Academy PRO: ES2015
Academy PRO: ES2015Academy PRO: ES2015
Academy PRO: ES2015
 
Jscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScriptJscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScript
 
ES6(ES2015) is beautiful
ES6(ES2015) is beautifulES6(ES2015) is beautiful
ES6(ES2015) is beautiful
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
 
ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
Node js
Node jsNode js
Node js
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
 
how to reuse code
how to reuse codehow to reuse code
how to reuse code
 
Javascript function
Javascript functionJavascript function
Javascript function
 
Javascript Uncommon Programming
Javascript Uncommon ProgrammingJavascript Uncommon Programming
Javascript Uncommon Programming
 
Jarmo van de Seijp Shadbox ERC223
Jarmo van de Seijp Shadbox ERC223Jarmo van de Seijp Shadbox ERC223
Jarmo van de Seijp Shadbox ERC223
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6
 
Selective codes
Selective codesSelective codes
Selective codes
 
Struct examples
Struct examplesStruct examples
Struct examples
 
Groovy grails types, operators, objects
Groovy grails types, operators, objectsGroovy grails types, operators, objects
Groovy grails types, operators, objects
 
Rxjs marble-testing
Rxjs marble-testingRxjs marble-testing
Rxjs marble-testing
 

More from Hanokh Aloni

NWD Total commander for fun and profit!!!
NWD Total commander for fun and profit!!!NWD Total commander for fun and profit!!!
NWD Total commander for fun and profit!!!Hanokh Aloni
 
CI CD OPS WHATHAVEYOU
CI CD OPS WHATHAVEYOUCI CD OPS WHATHAVEYOU
CI CD OPS WHATHAVEYOUHanokh Aloni
 
How to write proper GIT commit messages.pptx
How to write proper GIT commit messages.pptxHow to write proper GIT commit messages.pptx
How to write proper GIT commit messages.pptxHanokh Aloni
 
Architectural kata 0 of n.pptx
Architectural kata 0 of n.pptxArchitectural kata 0 of n.pptx
Architectural kata 0 of n.pptxHanokh Aloni
 
Code smells (1).pptx
Code smells (1).pptxCode smells (1).pptx
Code smells (1).pptxHanokh Aloni
 
top developer mistakes
top developer mistakes top developer mistakes
top developer mistakes Hanokh Aloni
 
Things senior developers should know
Things senior developers should knowThings senior developers should know
Things senior developers should knowHanokh Aloni
 
Cynefin framework in software engineering
Cynefin framework in software engineeringCynefin framework in software engineering
Cynefin framework in software engineeringHanokh Aloni
 
Trunk based vs git flow
Trunk based vs git flowTrunk based vs git flow
Trunk based vs git flowHanokh Aloni
 
How to write unmaintainable code
How to write unmaintainable codeHow to write unmaintainable code
How to write unmaintainable codeHanokh Aloni
 
How i learned to stop worrying and love the logs
How i learned to stop worrying and love the logsHow i learned to stop worrying and love the logs
How i learned to stop worrying and love the logsHanokh Aloni
 
Game is ggj2018 presentation
Game is ggj2018 presentationGame is ggj2018 presentation
Game is ggj2018 presentationHanokh Aloni
 
Game is ggj2017 presentation
Game is ggj2017 presentationGame is ggj2017 presentation
Game is ggj2017 presentationHanokh Aloni
 
02 terms and issues
02 terms and issues02 terms and issues
02 terms and issuesHanokh Aloni
 

More from Hanokh Aloni (20)

NWD Total commander for fun and profit!!!
NWD Total commander for fun and profit!!!NWD Total commander for fun and profit!!!
NWD Total commander for fun and profit!!!
 
CI CD OPS WHATHAVEYOU
CI CD OPS WHATHAVEYOUCI CD OPS WHATHAVEYOU
CI CD OPS WHATHAVEYOU
 
How to write proper GIT commit messages.pptx
How to write proper GIT commit messages.pptxHow to write proper GIT commit messages.pptx
How to write proper GIT commit messages.pptx
 
Architectural kata 0 of n.pptx
Architectural kata 0 of n.pptxArchitectural kata 0 of n.pptx
Architectural kata 0 of n.pptx
 
Code smells (1).pptx
Code smells (1).pptxCode smells (1).pptx
Code smells (1).pptx
 
top developer mistakes
top developer mistakes top developer mistakes
top developer mistakes
 
Things senior developers should know
Things senior developers should knowThings senior developers should know
Things senior developers should know
 
Cynefin framework in software engineering
Cynefin framework in software engineeringCynefin framework in software engineering
Cynefin framework in software engineering
 
Microservices
MicroservicesMicroservices
Microservices
 
Wcbpijwbpij new
Wcbpijwbpij newWcbpijwbpij new
Wcbpijwbpij new
 
Trunk based vs git flow
Trunk based vs git flowTrunk based vs git flow
Trunk based vs git flow
 
How to write unmaintainable code
How to write unmaintainable codeHow to write unmaintainable code
How to write unmaintainable code
 
How i learned to stop worrying and love the logs
How i learned to stop worrying and love the logsHow i learned to stop worrying and love the logs
How i learned to stop worrying and love the logs
 
Game is ggj2018 presentation
Game is ggj2018 presentationGame is ggj2018 presentation
Game is ggj2018 presentation
 
Microservices
MicroservicesMicroservices
Microservices
 
Game is ggj2017 presentation
Game is ggj2017 presentationGame is ggj2017 presentation
Game is ggj2017 presentation
 
02 terms and issues
02 terms and issues02 terms and issues
02 terms and issues
 
Sip introduction
Sip introductionSip introduction
Sip introduction
 
Tdd guide
Tdd guideTdd guide
Tdd guide
 
Git
GitGit
Git
 

Recently uploaded

Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptSAURABHKUMAR892774
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxKartikeyaDwivedi3
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
Mine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptxMine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptxRomil Mishra
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catcherssdickerson1
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxk795866
 
Virtual memory management in Operating System
Virtual memory management in Operating SystemVirtual memory management in Operating System
Virtual memory management in Operating SystemRashmi Bhat
 
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTIONTHE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTIONjhunlian
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...asadnawaz62
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
National Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdfNational Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdfRajuKanojiya4
 
Transport layer issues and challenges - Guide
Transport layer issues and challenges - GuideTransport layer issues and challenges - Guide
Transport layer issues and challenges - GuideGOPINATHS437943
 
Solving The Right Triangles PowerPoint 2.ppt
Solving The Right Triangles PowerPoint 2.pptSolving The Right Triangles PowerPoint 2.ppt
Solving The Right Triangles PowerPoint 2.pptJasonTagapanGulla
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfROCENODodongVILLACER
 
Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleAlluxio, Inc.
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
Class 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm SystemClass 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm Systemirfanmechengr
 

Recently uploaded (20)

Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.ppt
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptx
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
Mine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptxMine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptx
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptx
 
Virtual memory management in Operating System
Virtual memory management in Operating SystemVirtual memory management in Operating System
Virtual memory management in Operating System
 
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTIONTHE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
National Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdfNational Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdf
 
Transport layer issues and challenges - Guide
Transport layer issues and challenges - GuideTransport layer issues and challenges - Guide
Transport layer issues and challenges - Guide
 
Solving The Right Triangles PowerPoint 2.ppt
Solving The Right Triangles PowerPoint 2.pptSolving The Right Triangles PowerPoint 2.ppt
Solving The Right Triangles PowerPoint 2.ppt
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdf
 
Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at Scale
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
Class 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm SystemClass 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm System
 

NWD the73js.pptx

  • 1.
  • 3. Let’s implement the 73 calculator f(x) = { 3, x=7 7, x=3 ¯_(ツ)_/¯, otherwise }
  • 4.
  • 5. Let’s implement the 73 calculator f(x) = { 3, x=7 7, x=3 ¯_(ツ)_/¯, otherwise }
  • 6. Use an if static useif(n) { if (n == 3) return 7; return 3; }
  • 7. Use an if (the strict equality version) static useifeq(n) { if (n === 3) return 7; return 3; }
  • 8. Use a Xor static useXor(n) { return (n ^= 4); }
  • 9. Use an array static useArray(n) { const mem = [-1,-1,-1,7,-1,-1,-1,3]; return mem[n]; }
  • 10. The switch statement static useSwitch(n) { switch (n) { case 7: return 3; case 3: return 7; default: throw new exception("err"); } }
  • 13. String replace (I asked for a number) static stringReplaceNumber(n) { return Number("37".replace(n, "")); }
  • 14. String replace (I’ll parse you a number) static stringReplaceParseInt(n) { return parseInt("37".replace(n, "")); }
  • 15. Using modulo static useModulo(n) { return ((n + 4) % 8); }
  • 16. Using object map static useObjectMap(n) { const objmapper = { 3: 7, 7: 3 }; return objmapper[n]; }
  • 17. Using indexer dictionary static useIndexerDictionary(n) { const dict = {}; dict[3] = 7; dict[7] = 3; return dict[n]; }
  • 18. Using a Polynom static usePolynom(n) { return ((79 - (n * n)) / 10); }
  • 19. Let’s try another base static useOctalCast(n) { let numberAsOctal = (n + 4).toString(8) return parseInt(numberAsOctal) % 10; }
  • 20. I bet there are a couple more ways… Using relational databases, AI, routing, statistics, fourier transforms, various functional bases, and the sky is the limit…
  • 21. There’s more than one way to skin a cat
  • 23. Let’s find out which is best!
  • 25. var Benchmark = require('benchmark'); var suite = new Benchmark.Suite; const The73Calculator = require("./The73Calculator.js"); suite.add(The73Calculator.useif.name, () => { expectBehavior(The73Calculator.useif); }) .add(The73Calculator.useifeq.name, () => { expectBehavior(The73Calculator.useifeq); }) .add(The73Calculator.useXor.name, () => { expectBehavior(The73Calculator.useXor); }) .add(The73Calculator.useArray.name, () => { expectBehavior(The73Calculator.useArray); }) .add(The73Calculator.usingSwitch.name, () => { expectBehavior(The73Calculator.usingSwitch); }) .add(The73Calculator.useSubstraction.name, () => { expectBehavior(The73Calculator.useSubstraction); }) .add(The73Calculator.useDivision.name, () => { expectBehavior(The73Calculator.useDivision); }) .add(The73Calculator.useStringReplaceParseInt.name, () => { expectBehavior(The73Calculator.useStringReplaceParseInt);
  • 26. // add listeners .on('cycle', function(event) { console.log(String(event.target)); }) .on('complete', function() { report.sort((a, b) => (b.hz - a.hz)); report.forEach(r => console.log(r.name + " - " + r.hz)); console.log('Fastest is ' + this.filter('fastest').map('name')); console.log('Slowest is ' + this.filter('slowest').map('name')); }) // run async .run({ 'async': true }); function expectBehavior(f) { for (var i = 0; i < 100000; i++) { f(3); f(7); } }
  • 28. And the winner is… If Ifeq Substraction Division Xor Polynom Modulo Switch Array Octal IndexerDictionary StringReplaceNumber StringReplaceParseInt ObjectMap
  • 29. And the loser is… If Ifeq Substraction Division Xor Polynom Modulo Switch Array Octal IndexerDictionary StringReplaceNumber StringReplaceParseInt ObjectMap
  • 32. javascript Method runtime (us) useif 24.52 useXor 827 useSubstraction 951 useifeq 956 usingSwitch 1012 useArray 1228 usingPolynom 1349 usingModulo 1547 division 1848 usingObjectMap 4950 octal 12938 usingIndexerDictionary 40371 stringReplaceNumber 48875 stringReplaceParseInt 64267
  • 33. javascript c# Method runtime (us) runtime (ns) useif 24.52 485 useXor 827 437 useSubstraction 951 428 useifeq 956 498 usingSwitch 1012 501 useArray 1228 437 usingPolynom 1349 486 usingModulo 1547 432 division 1848 554 usingObjectMap 4950 4255 octal 12938 n/a usingIndexerDictionary 40371 1335 stringReplaceNumber 48875 n/a stringReplaceParseInt 64267 8474
  • 34. You have to measure to know
  • 35. If you haven’t measured, you don’t know
  • 36. If you think you know, and you haven’t measured, you still don’t know
  • 37. Now what? (2 of n)
  • 38. javascript c# Method runtime (us) runtime (ns) useif 24.52 485 useXor 827 437 useSubstraction 951 428 useifeq 956 498 usingSwitch 1012 501 useArray 1228 437 usingPolynom 1349 486 usingModulo 1547 432 division 1848 554 usingObjectMap 4950 4255 octal 12938 n/a usingIndexerDictionary 40371 1335 stringReplaceNumber 48875 n/a stringReplaceParseInt 64267 8474
  • 39. javascript c# Method runtime (us) runtime (ns) useif 24.52 485 useXor 827 437 useSubstraction 951 428 useifeq 956 498 usingSwitch 1012 501 useArray 1228 437 usingPolynom 1349 486 usingModulo 1547 432 division 1848 554 usingObjectMap 4950 4255 octal 12938 n/a usingIndexerDictionary 40371 1335 stringReplaceNumber 48875 n/a stringReplaceParseInt 64267 8474 By that much? This is interesting #1 This is interesting #2
  • 40. You are a victim of branch prediction fail.
  • 41.
  • 42. Summary There’s more than one way to skin a cat You have to measure to know Benchmark.js is great Energy awareness is a thing