SlideShare a Scribd company logo
MANUAL SPECIALIZATION
Szymon Matejczyk
@szymonmatejczyk
ACT 1:
WORLD RUINED
HIPSTERVS. OLDSCHOOL
def hipsterMin(a: Array[Int]): Int = {

a.foldLeft(Int.MaxValue){ _.min(_)}

}
def oldschoolMin(a: Array[Int]): Int = {

var min = Int.MaxValue

var i = 0

while (i < a.length) {

min = if (a(i) < min) a(i) else min

i += 1

}

min

}
HIPSTERVS. OLDSCHOOL
def hipsterMin(a: Array[Int]): Int = {

a.foldLeft(Int.MaxValue){ _.min(_)}

}
def oldschoolMin(a: Array[Int]): Int = {

var min = Int.MaxValue

var i = 0

while (i < a.length) {

min = if (a(i) < min) a(i) else min

i += 1

}

min

}
Running time
967722
123424
ACT 1I:
DENIAL
OLDSCHOOL
public int oldschoolMin(int[]);

Code:

0: ldc #72 // int 2147483647

2: istore_2

3: iconst_0

4: istore_3

5: iload_3

6: aload_1

7: arraylength

8: if_icmpge 33

11: aload_1

12: iload_3

13: iaload

14: iload_2

15: if_icmpge 24

18: aload_1

19: iload_3

20: iaload

21: goto 25

24: iload_2

25: istore_2

26: iload_3

27: iconst_1

28: iadd

29: istore_3

30: goto 5

33: iload_2

34: ireturn
HIPSTER
public int hipsterMin(int[]);

Code:

0: getstatic #67 // Field scala/Predef$.MODULE
$:Lscala/Predef$;

3: aload_1

4: invokevirtual #71 // Method scala/Predef
$.intArrayOps:([I)Lscala/collection/mutable/ArrayOps;

7: ldc #72 // int 2147483647

9: invokestatic #78 // Method scala/runtime/
BoxesRunTime.boxToInteger:(I)Ljava/lang/Integer;

12: new #80 // class szymon/Test$$anonfun
$hipsterMin$1

15: dup

16: aload_0

17: invokespecial #83 // Method szymon/Test$$anonfun
$hipsterMin$1."<init>":(Lszymon/Test;)V

20: invokeinterface #89, 3 // InterfaceMethod scala/
collection/mutable/ArrayOps.foldLeft:(Ljava/lang/Object;Lscala/
Function2;)Ljava/lang/Object;

25: invokestatic #93 // Method scala/runtime/
BoxesRunTime.unboxToInt:(Ljava/lang/Object;)I

28: ireturn
HIPSTER
public final class szymon.Test$$anonfun$hipsterMin$1 extends scala.runtime.AbstractFunction2$mcIII$sp
implements scala.Serializable {

public static final long serialVersionUID;



public final int apply(int, int);

Code:

0: aload_0

1: iload_1

2: iload_2

3: invokevirtual #21 // Method apply$mcIII$sp:(II)I

6: ireturn



public int apply$mcIII$sp(int, int);

Code:

0: getstatic #32 // Field scala/runtime/RichInt$.MODULE$:Lscala/runtime/RichInt$;

3: getstatic #37 // Field scala/Predef$.MODULE$:Lscala/Predef$;

6: iload_1

7: invokevirtual #41 // Method scala/Predef$.intWrapper:(I)I

10: iload_2

11: invokevirtual #44 // Method scala/runtime/RichInt$.min$extension:(II)I

14: ireturn



public final java.lang.Object apply(java.lang.Object, java.lang.Object);

Code:

0: aload_0

1: aload_1

2: invokestatic #51 // Method scala/runtime/BoxesRunTime.unboxToInt:(Ljava/lang/
Object;)I

5: aload_2

6: invokestatic #51 // Method scala/runtime/BoxesRunTime.unboxToInt:(Ljava/lang/
Object;)I

9: invokevirtual #53 // Method apply:(II)I

12: invokestatic #57 // Method scala/runtime/BoxesRunTime.boxToInteger:(I)Ljava/lang/
Integer;

15: areturn



public szymon.Test$$anonfun$hipsterMin$1(szymon.Test);

Code:

0: aload_0

1: invokespecial #65 // Method scala/runtime/AbstractFunction2$mcIII$sp."<init>":()V

4: return
BOXING


public int apply$mcIII$sp(int, int);

Code:

0: getstatic #32 // Field scala/runtime/RichInt
$.MODULE$:Lscala/runtime/RichInt$;

3: getstatic #37 // Field scala/Predef$.MODULE
$:Lscala/Predef$;

6: iload_1

7: invokevirtual #41 // Method scala/Predef
$.intWrapper:(I)I

10: iload_2

11: invokevirtual #44 // Method scala/runtime/RichInt
$.min$extension:(II)I

14: ireturn



public final java.lang.Object apply(java.lang.Object, java.lang.Object);

Code:

0: aload_0

1: aload_1

2: invokestatic #51 // Method scala/runtime/
BoxesRunTime.unboxToInt:(Ljava/lang/Object;)I

5: aload_2

6: invokestatic #51 // Method scala/runtime/
BoxesRunTime.unboxToInt:(Ljava/lang/Object;)I

9: invokevirtual #53 // Method apply:(II)I

12: invokestatic #57 // Method scala/runtime/
BoxesRunTime.boxToInteger:(I)Ljava/lang/Integer;

15: areturn
BOXING: HOWTO AVOID
• don’t use generics!
• use libraries for high performance code
• specialization?!
WHY SPECIALIZATION FAILS?
STEP BACKTO JAVA
• Trove
• fastutil
• HPPC
import scala.collection.JavaConversions._
def newInt2IntOpenHashMap(): mutable.Map[Int, Int] =

new Int2IntOpenHashMap().asInstanceOf[jutil.Map[Int, Int]]
STEP BACKTO JAVA
• Trove
• fastutil
• HPPC
import scala.collection.JavaConversions._
def newInt2IntOpenHashMap(): mutable.Map[Int, Int] =

new Int2IntOpenHashMap().asInstanceOf[jutil.Map[Int, Int]]
ACT 1II:
SURVIVE IN BROKEN WORLD
SPECIALIZED QUEUE
trait CQueue[@specialized(Int, Long) T] {

/**

* @return Next element to be dequeued.

*/

def first(): T



/**

*

* @return Next element that is removed from the `CQueue`.

*/

def deque(): T



/**

* Adds element to the `CQueue`.

*/

def +=(elem: T)



def isEmpty: Boolean

}
IMPLEMENTATION
class CQueueAny[T, QueueType <: PriorityQueue[T]](protected val
underlying: QueueType)

extends CQueue[T] {

def +=(elem: T): Unit = underlying.enqueue(elem)

def deque(): T = underlying.dequeue()

override def first(): T = underlying.first()

override def isEmpty: Boolean = underlying.isEmpty

}



class CQueueInt[QueueType <: IntPriorityQueue](protected val
underlying: QueueType)

extends CQueue[Int] {

override def +=(elem: Int): Unit = underlying.enqueue(elem)

override def deque(): Int = underlying.dequeueInt()

override def first(): Int = underlying.firstInt()

override def isEmpty: Boolean = underlying.isEmpty

}
FACTORY
abstract class CQueueFactory[T] {

def fifo(): FIFO[T]

def priority(): CQueue[T]

def priority(order: Order[T]): CQueue[T]

}
private[collections] class CQueueFactoryAny[T] extends CQueueFactory[T] {

def fifo(): FIFO[T] = new CQueueAny[T, ObjectArrayFIFOQueue[T]](

new ObjectArrayFIFOQueue[T]()) with FIFO[T] {

override def enqueueFirst(elem: T): Unit =
underlying.enqueueFirst(elem)

}

}



private[collections] class CQueueFactoryInt extends CQueueFactory[Int] {

override def fifo() = new CQueueInt[IntArrayFIFOQueue](
new IntArrayFIFOQueue()) with FIFO[Int] {

def enqueueFirst(elem: Int): Unit = underlying.enqueueFirst(elem)

}

}
GLUE
object CQueue {

import Implicits._



def fifo[@specialized(Int, Long) T](): FIFO[T]= {

implicitly[CQueueFactory[T]].fifo()

}



trait LowerPriorityImplicit {

private val factoryAny = new CQueueFactoryAny[AnyRef]()

implicit def factoryAny[T]: CQueueFactory[T] =
factoryAny.asInstanceOf[CQueueFactory[T]]

}



trait LowPriorityImplicit extends LowerPriorityImplicit {

implicit val factoryInt: CQueueFactory[Int] = new CQueueFactoryInt()

}



object Implicits extends LowPriorityImplicit

}
USAGEclass CQueueSpec extends WordSpec with Matchers {

def verifyQueue(q: CQueue[Int], dequeSeq: Seq[Int]): Unit = {

q.isEmpty should be (true)



q += 1

q += 2

q += 1

q += 3



q.isEmpty should be (false)



dequeSeq.foreach {

e => q.deque() should equal (e)

}

q.isEmpty should be (true)



intercept[NoSuchElementException](q.deque())

}



"CQueue" should {

"enqueue/deque elements" when {

"using fifo" in {

val q = CQueue.fifo[Int]()

verifyQueue(q, Seq(1, 2, 1, 3))

}

}

}

}
ACT IV:
MACROS!!
REKLAMY

More Related Content

What's hot

Chapter 7 functions (c)
Chapter 7 functions (c)Chapter 7 functions (c)
Chapter 7 functions (c)
hhliu
 
프알못의 Keras 사용기
프알못의 Keras 사용기프알못의 Keras 사용기
프알못의 Keras 사용기
Mijeong Jeon
 
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf MilanFrom Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
Fabio Collini
 
iOS와 케라스의 만남
iOS와 케라스의 만남iOS와 케라스의 만남
iOS와 케라스의 만남
Mijeong Jeon
 
Functions, Types, Programs and Effects
Functions, Types, Programs and EffectsFunctions, Types, Programs and Effects
Functions, Types, Programs and Effects
Raymond Roestenburg
 
Java simple programs
Java simple programsJava simple programs
Java simple programs
VEERA RAGAVAN
 
Initial Java Core Concept
Initial Java Core ConceptInitial Java Core Concept
Initial Java Core Concept
Rays Technologies
 
One Monad to Rule Them All
One Monad to Rule Them AllOne Monad to Rule Them All
One Monad to Rule Them All
John De Goes
 
Humble introduction to category theory in haskell
Humble introduction to category theory in haskellHumble introduction to category theory in haskell
Humble introduction to category theory in haskell
Jongsoo Lee
 
Introduction to functional programming using Ocaml
Introduction to functional programming using OcamlIntroduction to functional programming using Ocaml
Introduction to functional programming using Ocaml
pramode_ce
 
Pydiomatic
PydiomaticPydiomatic
Pydiomatic
rik0
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascript
Miao Siyu
 
响应式编程及框架
响应式编程及框架响应式编程及框架
响应式编程及框架
jeffz
 
Collection v3
Collection v3Collection v3
Collection v3
Sunil OS
 
Use Applicative where applicable!
Use Applicative where applicable!Use Applicative where applicable!
Use Applicative where applicable!
Hermann Hueck
 
Akka tips
Akka tipsAkka tips
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple Programs
Upender Upr
 
Swift internals
Swift internalsSwift internals
Swift internals
Jung Kim
 
The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)
jeffz
 
Object Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in PythonObject Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in Python
Tendayi Mawushe
 

What's hot (20)

Chapter 7 functions (c)
Chapter 7 functions (c)Chapter 7 functions (c)
Chapter 7 functions (c)
 
프알못의 Keras 사용기
프알못의 Keras 사용기프알못의 Keras 사용기
프알못의 Keras 사용기
 
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf MilanFrom Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
 
iOS와 케라스의 만남
iOS와 케라스의 만남iOS와 케라스의 만남
iOS와 케라스의 만남
 
Functions, Types, Programs and Effects
Functions, Types, Programs and EffectsFunctions, Types, Programs and Effects
Functions, Types, Programs and Effects
 
Java simple programs
Java simple programsJava simple programs
Java simple programs
 
Initial Java Core Concept
Initial Java Core ConceptInitial Java Core Concept
Initial Java Core Concept
 
One Monad to Rule Them All
One Monad to Rule Them AllOne Monad to Rule Them All
One Monad to Rule Them All
 
Humble introduction to category theory in haskell
Humble introduction to category theory in haskellHumble introduction to category theory in haskell
Humble introduction to category theory in haskell
 
Introduction to functional programming using Ocaml
Introduction to functional programming using OcamlIntroduction to functional programming using Ocaml
Introduction to functional programming using Ocaml
 
Pydiomatic
PydiomaticPydiomatic
Pydiomatic
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascript
 
响应式编程及框架
响应式编程及框架响应式编程及框架
响应式编程及框架
 
Collection v3
Collection v3Collection v3
Collection v3
 
Use Applicative where applicable!
Use Applicative where applicable!Use Applicative where applicable!
Use Applicative where applicable!
 
Akka tips
Akka tipsAkka tips
Akka tips
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple Programs
 
Swift internals
Swift internalsSwift internals
Swift internals
 
The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)
 
Object Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in PythonObject Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in Python
 

Viewers also liked

Como acreditar los derechos del autor
Como acreditar los derechos del autorComo acreditar los derechos del autor
Como acreditar los derechos del autor
201577102547572
 
Brunner_Andrea_DOS_2015
Brunner_Andrea_DOS_2015Brunner_Andrea_DOS_2015
Brunner_Andrea_DOS_2015Andrea Brunner
 
Progress Monitoring Interpretation
Progress Monitoring InterpretationProgress Monitoring Interpretation
Progress Monitoring Interpretation
Madison Hopkins
 
Herramientas de google
Herramientas de googleHerramientas de google
Herramientas de google
Jenifer Procel
 
Certificate of completion for Project+ 2015
Certificate of completion for Project+ 2015Certificate of completion for Project+ 2015
Certificate of completion for Project+ 2015
barnesjohn
 
Zodiac theme park1
Zodiac theme park1Zodiac theme park1
Zodiac theme park1
Dmitry Dudziuk
 
Killeen Parks Master Plan
Killeen Parks Master PlanKilleen Parks Master Plan
Killeen Parks Master Plan
CityofKilleen
 
Curiositats animals
Curiositats animalsCuriositats animals
Curiositats animals
mertxita
 
Past Continuous: free time activities
Past Continuous: free time activitiesPast Continuous: free time activities
Past Continuous: free time activities
peggym26
 
MENU2016PDF copy
MENU2016PDF copyMENU2016PDF copy
MENU2016PDF copy
Duke Vonggaveesakul
 
Instructional Design Presentation
Instructional Design PresentationInstructional Design Presentation
Instructional Design Presentation
Candace Ward
 
Tips for Successful Residential Property Tax Appeals
Tips for Successful Residential Property Tax AppealsTips for Successful Residential Property Tax Appeals
Tips for Successful Residential Property Tax Appeals
Curley & Rothman, LLC
 
Світіння моря
Світіння моряСвітіння моря
Світіння моря
Елена Мешкова
 
TJ-SP 2017 - Matéria- CONCURSO ASSISTENTE SOCIAL JUDICIÁRIO-
TJ-SP 2017 - Matéria- CONCURSO ASSISTENTE SOCIAL JUDICIÁRIO- TJ-SP 2017 - Matéria- CONCURSO ASSISTENTE SOCIAL JUDICIÁRIO-
TJ-SP 2017 - Matéria- CONCURSO ASSISTENTE SOCIAL JUDICIÁRIO-
Rosane Domingues
 

Viewers also liked (15)

Como acreditar los derechos del autor
Como acreditar los derechos del autorComo acreditar los derechos del autor
Como acreditar los derechos del autor
 
Brunner_Andrea_DOS_2015
Brunner_Andrea_DOS_2015Brunner_Andrea_DOS_2015
Brunner_Andrea_DOS_2015
 
MY NEW EXHIBITION
MY NEW EXHIBITIONMY NEW EXHIBITION
MY NEW EXHIBITION
 
Progress Monitoring Interpretation
Progress Monitoring InterpretationProgress Monitoring Interpretation
Progress Monitoring Interpretation
 
Herramientas de google
Herramientas de googleHerramientas de google
Herramientas de google
 
Certificate of completion for Project+ 2015
Certificate of completion for Project+ 2015Certificate of completion for Project+ 2015
Certificate of completion for Project+ 2015
 
Zodiac theme park1
Zodiac theme park1Zodiac theme park1
Zodiac theme park1
 
Killeen Parks Master Plan
Killeen Parks Master PlanKilleen Parks Master Plan
Killeen Parks Master Plan
 
Curiositats animals
Curiositats animalsCuriositats animals
Curiositats animals
 
Past Continuous: free time activities
Past Continuous: free time activitiesPast Continuous: free time activities
Past Continuous: free time activities
 
MENU2016PDF copy
MENU2016PDF copyMENU2016PDF copy
MENU2016PDF copy
 
Instructional Design Presentation
Instructional Design PresentationInstructional Design Presentation
Instructional Design Presentation
 
Tips for Successful Residential Property Tax Appeals
Tips for Successful Residential Property Tax AppealsTips for Successful Residential Property Tax Appeals
Tips for Successful Residential Property Tax Appeals
 
Світіння моря
Світіння моряСвітіння моря
Світіння моря
 
TJ-SP 2017 - Matéria- CONCURSO ASSISTENTE SOCIAL JUDICIÁRIO-
TJ-SP 2017 - Matéria- CONCURSO ASSISTENTE SOCIAL JUDICIÁRIO- TJ-SP 2017 - Matéria- CONCURSO ASSISTENTE SOCIAL JUDICIÁRIO-
TJ-SP 2017 - Matéria- CONCURSO ASSISTENTE SOCIAL JUDICIÁRIO-
 

Similar to Manual specialization

DjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New RelicDjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New Relic
Graham Dumpleton
 
Djangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New RelicDjangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New Relic
New Relic
 
FS2 for Fun and Profit
FS2 for Fun and ProfitFS2 for Fun and Profit
FS2 for Fun and Profit
Adil Akhter
 
Smalltalk blocks and closures origin and evolution by Juan Escalada
Smalltalk blocks and closures origin and evolution by Juan EscaladaSmalltalk blocks and closures origin and evolution by Juan Escalada
Smalltalk blocks and closures origin and evolution by Juan Escalada
FAST
 
Kotlin Perfomance on Android / Александр Смирнов (Splyt)
Kotlin Perfomance on Android / Александр Смирнов (Splyt)Kotlin Perfomance on Android / Александр Смирнов (Splyt)
Kotlin Perfomance on Android / Александр Смирнов (Splyt)
Ontico
 
What's in Kotlin for us - Alexandre Greschon, MyHeritage
What's in Kotlin for us - Alexandre Greschon, MyHeritageWhat's in Kotlin for us - Alexandre Greschon, MyHeritage
What's in Kotlin for us - Alexandre Greschon, MyHeritage
DroidConTLV
 
C++ Searching & Sorting5. Sort the following list using the select.pdf
C++ Searching & Sorting5. Sort the following list using the select.pdfC++ Searching & Sorting5. Sort the following list using the select.pdf
C++ Searching & Sorting5. Sort the following list using the select.pdf
Rahul04August
 
Ruby tricks2
Ruby tricks2Ruby tricks2
Ruby tricks2
Michał Łomnicki
 
Scala coated JVM
Scala coated JVMScala coated JVM
Scala coated JVM
Stuart Roebuck
 
Introducción a Elixir
Introducción a ElixirIntroducción a Elixir
Introducción a Elixir
Svet Ivantchev
 
Swift Sequences & Collections
Swift Sequences & CollectionsSwift Sequences & Collections
Swift Sequences & Collections
CocoaHeads France
 
Python profiling
Python profilingPython profiling
Python profiling
dreampuf
 
Is java8 a true functional programming language
Is java8 a true functional programming languageIs java8 a true functional programming language
Is java8 a true functional programming language
SQLI
 
Is java8a truefunctionallanguage
Is java8a truefunctionallanguageIs java8a truefunctionallanguage
Is java8a truefunctionallanguage
Samir Chekkal
 
Implementing stack
Implementing stackImplementing stack
Implementing stack
mohamed sikander
 
Play image
Play imagePlay image
Play image
Fardian Syah
 
Blending Culture in Twitter Client
Blending Culture in Twitter ClientBlending Culture in Twitter Client
Blending Culture in Twitter Client
Kenji Tanaka
 
PRACTICAL COMPUTING
PRACTICAL COMPUTINGPRACTICAL COMPUTING
PRACTICAL COMPUTING
Ramachendran Logarajah
 
Gevent what's the point
Gevent what's the pointGevent what's the point
Gevent what's the point
seanmcq
 
Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
Shaul Rosenzwieg
 

Similar to Manual specialization (20)

DjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New RelicDjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New Relic
 
Djangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New RelicDjangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New Relic
 
FS2 for Fun and Profit
FS2 for Fun and ProfitFS2 for Fun and Profit
FS2 for Fun and Profit
 
Smalltalk blocks and closures origin and evolution by Juan Escalada
Smalltalk blocks and closures origin and evolution by Juan EscaladaSmalltalk blocks and closures origin and evolution by Juan Escalada
Smalltalk blocks and closures origin and evolution by Juan Escalada
 
Kotlin Perfomance on Android / Александр Смирнов (Splyt)
Kotlin Perfomance on Android / Александр Смирнов (Splyt)Kotlin Perfomance on Android / Александр Смирнов (Splyt)
Kotlin Perfomance on Android / Александр Смирнов (Splyt)
 
What's in Kotlin for us - Alexandre Greschon, MyHeritage
What's in Kotlin for us - Alexandre Greschon, MyHeritageWhat's in Kotlin for us - Alexandre Greschon, MyHeritage
What's in Kotlin for us - Alexandre Greschon, MyHeritage
 
C++ Searching & Sorting5. Sort the following list using the select.pdf
C++ Searching & Sorting5. Sort the following list using the select.pdfC++ Searching & Sorting5. Sort the following list using the select.pdf
C++ Searching & Sorting5. Sort the following list using the select.pdf
 
Ruby tricks2
Ruby tricks2Ruby tricks2
Ruby tricks2
 
Scala coated JVM
Scala coated JVMScala coated JVM
Scala coated JVM
 
Introducción a Elixir
Introducción a ElixirIntroducción a Elixir
Introducción a Elixir
 
Swift Sequences & Collections
Swift Sequences & CollectionsSwift Sequences & Collections
Swift Sequences & Collections
 
Python profiling
Python profilingPython profiling
Python profiling
 
Is java8 a true functional programming language
Is java8 a true functional programming languageIs java8 a true functional programming language
Is java8 a true functional programming language
 
Is java8a truefunctionallanguage
Is java8a truefunctionallanguageIs java8a truefunctionallanguage
Is java8a truefunctionallanguage
 
Implementing stack
Implementing stackImplementing stack
Implementing stack
 
Play image
Play imagePlay image
Play image
 
Blending Culture in Twitter Client
Blending Culture in Twitter ClientBlending Culture in Twitter Client
Blending Culture in Twitter Client
 
PRACTICAL COMPUTING
PRACTICAL COMPUTINGPRACTICAL COMPUTING
PRACTICAL COMPUTING
 
Gevent what's the point
Gevent what's the pointGevent what's the point
Gevent what's the point
 
Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
 

Recently uploaded

Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
shyamraj55
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website
Pixlogix Infotech
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Data structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdfData structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdf
TIPNGVN2
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
Rohit Gautam
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
Daiki Mogmet Ito
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
Neo4j
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIEnchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Vladimir Iglovikov, Ph.D.
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 

Recently uploaded (20)

Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Data structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdfData structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdf
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIEnchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 

Manual specialization

  • 3. HIPSTERVS. OLDSCHOOL def hipsterMin(a: Array[Int]): Int = {
 a.foldLeft(Int.MaxValue){ _.min(_)}
 } def oldschoolMin(a: Array[Int]): Int = {
 var min = Int.MaxValue
 var i = 0
 while (i < a.length) {
 min = if (a(i) < min) a(i) else min
 i += 1
 }
 min
 }
  • 4. HIPSTERVS. OLDSCHOOL def hipsterMin(a: Array[Int]): Int = {
 a.foldLeft(Int.MaxValue){ _.min(_)}
 } def oldschoolMin(a: Array[Int]): Int = {
 var min = Int.MaxValue
 var i = 0
 while (i < a.length) {
 min = if (a(i) < min) a(i) else min
 i += 1
 }
 min
 } Running time 967722 123424
  • 5.
  • 7. OLDSCHOOL public int oldschoolMin(int[]);
 Code:
 0: ldc #72 // int 2147483647
 2: istore_2
 3: iconst_0
 4: istore_3
 5: iload_3
 6: aload_1
 7: arraylength
 8: if_icmpge 33
 11: aload_1
 12: iload_3
 13: iaload
 14: iload_2
 15: if_icmpge 24
 18: aload_1
 19: iload_3
 20: iaload
 21: goto 25
 24: iload_2
 25: istore_2
 26: iload_3
 27: iconst_1
 28: iadd
 29: istore_3
 30: goto 5
 33: iload_2
 34: ireturn
  • 8. HIPSTER public int hipsterMin(int[]);
 Code:
 0: getstatic #67 // Field scala/Predef$.MODULE $:Lscala/Predef$;
 3: aload_1
 4: invokevirtual #71 // Method scala/Predef $.intArrayOps:([I)Lscala/collection/mutable/ArrayOps;
 7: ldc #72 // int 2147483647
 9: invokestatic #78 // Method scala/runtime/ BoxesRunTime.boxToInteger:(I)Ljava/lang/Integer;
 12: new #80 // class szymon/Test$$anonfun $hipsterMin$1
 15: dup
 16: aload_0
 17: invokespecial #83 // Method szymon/Test$$anonfun $hipsterMin$1."<init>":(Lszymon/Test;)V
 20: invokeinterface #89, 3 // InterfaceMethod scala/ collection/mutable/ArrayOps.foldLeft:(Ljava/lang/Object;Lscala/ Function2;)Ljava/lang/Object;
 25: invokestatic #93 // Method scala/runtime/ BoxesRunTime.unboxToInt:(Ljava/lang/Object;)I
 28: ireturn
  • 9. HIPSTER public final class szymon.Test$$anonfun$hipsterMin$1 extends scala.runtime.AbstractFunction2$mcIII$sp implements scala.Serializable {
 public static final long serialVersionUID;
 
 public final int apply(int, int);
 Code:
 0: aload_0
 1: iload_1
 2: iload_2
 3: invokevirtual #21 // Method apply$mcIII$sp:(II)I
 6: ireturn
 
 public int apply$mcIII$sp(int, int);
 Code:
 0: getstatic #32 // Field scala/runtime/RichInt$.MODULE$:Lscala/runtime/RichInt$;
 3: getstatic #37 // Field scala/Predef$.MODULE$:Lscala/Predef$;
 6: iload_1
 7: invokevirtual #41 // Method scala/Predef$.intWrapper:(I)I
 10: iload_2
 11: invokevirtual #44 // Method scala/runtime/RichInt$.min$extension:(II)I
 14: ireturn
 
 public final java.lang.Object apply(java.lang.Object, java.lang.Object);
 Code:
 0: aload_0
 1: aload_1
 2: invokestatic #51 // Method scala/runtime/BoxesRunTime.unboxToInt:(Ljava/lang/ Object;)I
 5: aload_2
 6: invokestatic #51 // Method scala/runtime/BoxesRunTime.unboxToInt:(Ljava/lang/ Object;)I
 9: invokevirtual #53 // Method apply:(II)I
 12: invokestatic #57 // Method scala/runtime/BoxesRunTime.boxToInteger:(I)Ljava/lang/ Integer;
 15: areturn
 
 public szymon.Test$$anonfun$hipsterMin$1(szymon.Test);
 Code:
 0: aload_0
 1: invokespecial #65 // Method scala/runtime/AbstractFunction2$mcIII$sp."<init>":()V
 4: return
  • 10. BOXING 
 public int apply$mcIII$sp(int, int);
 Code:
 0: getstatic #32 // Field scala/runtime/RichInt $.MODULE$:Lscala/runtime/RichInt$;
 3: getstatic #37 // Field scala/Predef$.MODULE $:Lscala/Predef$;
 6: iload_1
 7: invokevirtual #41 // Method scala/Predef $.intWrapper:(I)I
 10: iload_2
 11: invokevirtual #44 // Method scala/runtime/RichInt $.min$extension:(II)I
 14: ireturn
 
 public final java.lang.Object apply(java.lang.Object, java.lang.Object);
 Code:
 0: aload_0
 1: aload_1
 2: invokestatic #51 // Method scala/runtime/ BoxesRunTime.unboxToInt:(Ljava/lang/Object;)I
 5: aload_2
 6: invokestatic #51 // Method scala/runtime/ BoxesRunTime.unboxToInt:(Ljava/lang/Object;)I
 9: invokevirtual #53 // Method apply:(II)I
 12: invokestatic #57 // Method scala/runtime/ BoxesRunTime.boxToInteger:(I)Ljava/lang/Integer;
 15: areturn
  • 11. BOXING: HOWTO AVOID • don’t use generics! • use libraries for high performance code • specialization?!
  • 13. STEP BACKTO JAVA • Trove • fastutil • HPPC import scala.collection.JavaConversions._ def newInt2IntOpenHashMap(): mutable.Map[Int, Int] =
 new Int2IntOpenHashMap().asInstanceOf[jutil.Map[Int, Int]]
  • 14. STEP BACKTO JAVA • Trove • fastutil • HPPC import scala.collection.JavaConversions._ def newInt2IntOpenHashMap(): mutable.Map[Int, Int] =
 new Int2IntOpenHashMap().asInstanceOf[jutil.Map[Int, Int]]
  • 15. ACT 1II: SURVIVE IN BROKEN WORLD
  • 16. SPECIALIZED QUEUE trait CQueue[@specialized(Int, Long) T] {
 /**
 * @return Next element to be dequeued.
 */
 def first(): T
 
 /**
 *
 * @return Next element that is removed from the `CQueue`.
 */
 def deque(): T
 
 /**
 * Adds element to the `CQueue`.
 */
 def +=(elem: T)
 
 def isEmpty: Boolean
 }
  • 17. IMPLEMENTATION class CQueueAny[T, QueueType <: PriorityQueue[T]](protected val underlying: QueueType)
 extends CQueue[T] {
 def +=(elem: T): Unit = underlying.enqueue(elem)
 def deque(): T = underlying.dequeue()
 override def first(): T = underlying.first()
 override def isEmpty: Boolean = underlying.isEmpty
 }
 
 class CQueueInt[QueueType <: IntPriorityQueue](protected val underlying: QueueType)
 extends CQueue[Int] {
 override def +=(elem: Int): Unit = underlying.enqueue(elem)
 override def deque(): Int = underlying.dequeueInt()
 override def first(): Int = underlying.firstInt()
 override def isEmpty: Boolean = underlying.isEmpty
 }
  • 18. FACTORY abstract class CQueueFactory[T] {
 def fifo(): FIFO[T]
 def priority(): CQueue[T]
 def priority(order: Order[T]): CQueue[T]
 } private[collections] class CQueueFactoryAny[T] extends CQueueFactory[T] {
 def fifo(): FIFO[T] = new CQueueAny[T, ObjectArrayFIFOQueue[T]](
 new ObjectArrayFIFOQueue[T]()) with FIFO[T] {
 override def enqueueFirst(elem: T): Unit = underlying.enqueueFirst(elem)
 }
 }
 
 private[collections] class CQueueFactoryInt extends CQueueFactory[Int] {
 override def fifo() = new CQueueInt[IntArrayFIFOQueue]( new IntArrayFIFOQueue()) with FIFO[Int] {
 def enqueueFirst(elem: Int): Unit = underlying.enqueueFirst(elem)
 }
 }
  • 19. GLUE object CQueue {
 import Implicits._
 
 def fifo[@specialized(Int, Long) T](): FIFO[T]= {
 implicitly[CQueueFactory[T]].fifo()
 }
 
 trait LowerPriorityImplicit {
 private val factoryAny = new CQueueFactoryAny[AnyRef]()
 implicit def factoryAny[T]: CQueueFactory[T] = factoryAny.asInstanceOf[CQueueFactory[T]]
 }
 
 trait LowPriorityImplicit extends LowerPriorityImplicit {
 implicit val factoryInt: CQueueFactory[Int] = new CQueueFactoryInt()
 }
 
 object Implicits extends LowPriorityImplicit
 }
  • 20. USAGEclass CQueueSpec extends WordSpec with Matchers {
 def verifyQueue(q: CQueue[Int], dequeSeq: Seq[Int]): Unit = {
 q.isEmpty should be (true)
 
 q += 1
 q += 2
 q += 1
 q += 3
 
 q.isEmpty should be (false)
 
 dequeSeq.foreach {
 e => q.deque() should equal (e)
 }
 q.isEmpty should be (true)
 
 intercept[NoSuchElementException](q.deque())
 }
 
 "CQueue" should {
 "enqueue/deque elements" when {
 "using fifo" in {
 val q = CQueue.fifo[Int]()
 verifyQueue(q, Seq(1, 2, 1, 3))
 }
 }
 }
 }