SlideShare a Scribd company logo
1 of 56
Download to read offline
Message In A
  Bottle
    Konstantin Haase
Ruby 1.8 is slow because it's interpreted.

 Surprise! Ruby 1.9 is interpreted, too.
Thanks!
github.com / rkh / presentations
Ruby
What We'll Look Into
  MRI: method dispatch and execution

    Rubinius: inline caches and JIT

        JRuby: invokedynamic
class DeepThought
  def ultimate_answer?(value)
    value.to_s == '42'
  end
end
DeepThought.new.ultimate_answer? 42
They Just Love Bytecode
Ruby
  value.to_s

MRI
  getlocal value
  send :to_s, 0, nil, 0, <ic:0>

Rubinius
  push_local 0
  send_stack :to_s, 0

JRuby
  ALOAD 0
  LDC "to_suffffNuffffu0000u0000u0001u0000u0000u0000u0000u0000u0000...
  INVOKEVIRTUAL org/jruby/ast/executable/AbstractScript.initFromDescriptor (Lj...
  ...
  ALOAD 0
  INVOKEVIRTUAL ruby/__dash_e__.getCallSite0 ()Lorg/jruby/runtime/CallSite;
  ALOAD 1
  ALOAD 2
  ALOAD 9
  INVOKEVIRTUAL org/jruby/runtime/CallSite.call (Lorg/jruby/runtime/ThreadCont...
The Plan
search for method

execute method
How To Speed That Up?
        search faster

        execute faster
Speed Up Search
Inline Cache (aka Call/Send Site Cache)

            Lookup Cache

                Inlining
Speed Up Execution
      Reduce operations

    Just-in-time compilation

            Inlining

       Speed up search
MRI
a method gets called

     rb_call0
static inline VALUE
rb_call0(VALUE recv, ID mid, int argc, const VALUE *argv,
         call_type scope, VALUE self)
{
    rb_method_entry_t *me = rb_search_method_entry(recv, mid);
    rb_thread_t *th = GET_THREAD();
    int call_status = rb_method_call_status(th, me, scope, self); // <- SEARCH
    if (call_status != NOEX_OK) {
      return method_missing(recv, mid, argc, argv, call_status);
    }
    stack_check();
    return vm_call0(th, recv, mid, argc, argv, me);                // <- EXECUTE
}
/*
  * rb_call0 searching for a method
  * -> rb_method_entry
  * -> rb_method_entry_get_without_cache
  * -> search_method
  */
static rb_method_entry_t*
search_method(VALUE klass, ID id)
{
     st_data_t body;
     if (!klass) {
       return 0;
     }

    while (!st_lookup(RCLASS_M_TBL(klass), id, &body)) {
      klass = RCLASS_SUPER(klass);
        if (!klass) {
          return 0;
        }
    }
    return (rb_method_entry_t *)body;
}
/*
  * rb_call0 executing a method
  * -> vm_call0
  */
static inline VALUE
vm_call0(rb_thread_t* th, VALUE recv, VALUE id, int argc, const VALUE *argv,
          const rb_method_entry_t *me)
{
     const rb_method_definition_t *def = me->def;
     VALUE val;
     const rb_block_t *blockptr = 0;
     // ...
    again:
      switch (def->type) {
        case VM_METHOD_TYPE_ISEQ: {
           rb_control_frame_t *reg_cfp;
           // ...
           vm_setup_method(th, reg_cfp, recv, argc, blockptr, 0 /* flag */, me);
           val = vm_exec(th); // <- EXECUTE !!!
           break;
        }
        // ...
      }
    // ...
}
static VALUE
vm_exec(rb_thread_t *th)
{
  // ... go see for yourself ...
}
DEFINE_INSN
send
(ID op_id, rb_num_t op_argc, ISEQ blockiseq, rb_num_t op_flag, IC ic)
(...)
(VALUE val)
// inc += - (int)(op_argc + ((op_flag & VM_CALL_ARGS_BLOCKARG_BIT) ? 1 : 0));
{
     const rb_method_entry_t *me;
     VALUE recv, klass;
     rb_block_t *blockptr = 0;
     VALUE flag = op_flag;
     int num = caller_setup_args(th, GET_CFP(), flag, (int)op_argc,
               (rb_iseq_t *)blockiseq, &blockptr);
     ID id = op_id;
    /* get receiver */
    recv = (flag & VM_CALL_FCALL_BIT) ? GET_SELF() : TOPN(num);
    klass = CLASS_OF(recv);
    me = vm_method_search(id, klass, ic);
    CALL_METHOD(num, blockptr, flag, id, me, recv);
}
Rubinius
klass = object.singleton_class
method = nil

while klass and not method
  method = klass.method_table.lookup(:some_method)
  klass = klass.direct_superclass
end
>> cm = DeepThought.method_table 
?>        .lookup(:ultimate_answer?).method
=> #<Rubinius::CompiledMethod ultimate_answer?>

>> puts cm.decode
0000: push_local                  0    # value
0002: send_stack                  :to_s, 0
0005: push_literal                "42"
0007: string_dup
0008: meta_send_op_equal          :==
0010: ret
=> nil
>> cm.iseq.opcodes
=> #<Rubinius::Tuple: 20, 0, 49, 0, 0, 7, 1, 64, 83, 2, 11>

>> cm.literals
=> #<Rubinius::Tuple: :to_s, "42", :==>
literals: :to_s, "42", :==   locals: value (42)
bytes: 20 0 49 0 0 7 1 64 83 2 11

bytes     decoded               stack
20 0      push_local 0          [ 42         ]
49 0 0    send_stack :to_s, 0   [ "42"       ]
7 1       push_literal "42"     [ "42", "42" ]
64        string_dup            [ "42", "42" ]
83 2      meta_send_op_equal    [ true       ]
11        ret                   [            ]
instruction send_stack(literal count) [ receiver +count -- value ] => send
  Object* recv = stack_back(count);
  InlineCache* cache = reinterpret_cast<InlineCache*>(literal);
  Arguments args(cache->name, recv, Qnil, count, stack_back_position(count));
  Object* ret = cache->execute(state, call_frame, args);
  CHECK_AND_PUSH(ret);
end
Specialized Methods
        cached bytecode

     code with breakpoints

    specialized for arguments

           JITed code
JRuby
INVOKEVIRTUAL
INVOKEVIRTUAL example.getCallSite1 ...
ALOAD 1
ALOAD 2
ALOAD 9
INVOKEVIRTUAL org/jruby/runtime/CallSite.call ...

                INVOKEDYNAMIC
ALOAD 1
ALOAD 2
ALOAD 9
INVOKEDYNAMIC call ...
INVOKEVIRTUAL
INVOKEVIRTUAL org/jruby/runtime/CallSite.call(
    Lorg/jruby/runtime/ThreadContext;
    Lorg/jruby/runtime/builtin/IRubyObject;
    Lorg/jruby/runtime/builtin/IRubyObject;
  )Lorg/jruby/runtime/builtin/IRubyObject;

                INVOKEDYNAMIC
INVOKEDYNAMIC call(
    Lorg/jruby/runtime/ThreadContext;
    Lorg/jruby/runtime/builtin/IRubyObject;
    Lorg/jruby/runtime/builtin/IRubyObject;
    Ljava/lang/String;
  )Lorg/jruby/runtime/builtin/IRubyObject;
  [...]
The Linker
[org/jruby/runtime/invokedynamic/InvocationLinker
  .invocationBootstrap(
    Ljava/lang/invoke/MethodHandles$Lookup;
    Ljava/lang/String;
    Ljava/lang/invoke/MethodType;
  )Ljava/lang/invoke/CallSite;]
The Bootstrap
public static CallSite
invocationBootstrap(Lookup lookup, String name, MethodType type)
throws NoSuchMethodException, IllegalAccessException {
  CallSite site;
  // ...
  if (name.equals("call")) {
    site = new JRubyCallSite(lookup, type, CallType.NORMAL, false, false, true);
  }
  // ...
  MethodHandle myFallback = ...
  site.setTarget(myFallback);
  return site;
}
The Fallback
public static IRubyObject invocationFallback(JRubyCallSite site,
    ThreadContext context,
    IRubyObject caller,
    IRubyObject self,
    String name) throws Throwable {
  RubyClass selfClass = pollAndGetClass(context, self);
  CacheEntry entry = selfClass.searchWithCache(name);
    if (methodMissing(entry, site.callType(), name, caller)) {
      return callMethodMissing(entry, site.callType(), context, self, name);
    }
    MethodHandle target = getTarget(site, selfClass, name, entry, 0);
    target = updateInvocationTarget(target, site, selfClass, name, entry, false, 0);
    return (IRubyObject)target.invokeWithArguments(context, caller, self, name);
}
images
                          http://kosmur.deviantart.com/art/assembler-79007314
                                     https://www.facebook.com/headius
                                  https://www.facebook.com/koichi.sasada
                          https://www.facebook.com/profile.php?id=523826914
                     http://farm4.static.flickr.com/3207/2522976901_6ff55314cd.jpg
                          http://www.flickr.com/photos/binkley27/3451700024
                             http://www.flickr.com/photos/funtik/1175522045
                          http://en.wikipedia.org/wiki/File:Answer_to_Life.png
                        http://www.flickr.com/photos/makelessnoise/195088755/
                         http://www.flickr.com/photos/jeffhenshaw/4833007463/
http://churchmusictoday.wordpress.com/2011/05/13/ten-warning-signs-for-churches-from-thom-ranier/
              http://www.freefoto.com/preview/28-06-3/Police-Underwater-Search-Unit
                 http://blog-blond.blogspot.com/2009/07/how-to-do-blogs-right.html
                 http://fuckyouverymuch.dk/post/9661487809/we-are-ready-to-leave
              http://crunchtools.com/bootstrapping-and-rooting-documentation-part-2/
                       http://www.softmyhard.com/tag/device-instruction-manual
                          http://www.flickr.com/photos/quinnanya/4874581964
Thanks!
github.com / rkh / presentations

More Related Content

What's hot

連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」matuura_core
 
Arduino coding class
Arduino coding classArduino coding class
Arduino coding classJonah Marrs
 
Practical JavaScript Programming - Session 6/8
Practical JavaScript Programming - Session 6/8Practical JavaScript Programming - Session 6/8
Practical JavaScript Programming - Session 6/8Wilson Su
 
Binaries Are Not Only Output
Binaries Are Not Only OutputBinaries Are Not Only Output
Binaries Are Not Only OutputHajime Morrita
 
The mighty js_function
The mighty js_functionThe mighty js_function
The mighty js_functiontimotheeg
 
Swiftの関数型っぽい部分
Swiftの関数型っぽい部分Swiftの関数型っぽい部分
Swiftの関数型っぽい部分bob_is_strange
 
Hacking parse.y (RubyKansai38)
Hacking parse.y (RubyKansai38)Hacking parse.y (RubyKansai38)
Hacking parse.y (RubyKansai38)ujihisa
 
HailDB: A NoSQL API Direct to InnoDB
HailDB: A NoSQL API Direct to InnoDBHailDB: A NoSQL API Direct to InnoDB
HailDB: A NoSQL API Direct to InnoDBstewartsmith
 
Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Platonov Sergey
 
Алексей Кутумов, Coroutines everywhere
Алексей Кутумов, Coroutines everywhereАлексей Кутумов, Coroutines everywhere
Алексей Кутумов, Coroutines everywhereSergey Platonov
 
Letswift18 워크숍#1 스위프트 클린코드와 코드리뷰
Letswift18 워크숍#1 스위프트 클린코드와 코드리뷰Letswift18 워크숍#1 스위프트 클린코드와 코드리뷰
Letswift18 워크숍#1 스위프트 클린코드와 코드리뷰Jung Kim
 
Lexical environment in ecma 262 5
Lexical environment in ecma 262 5Lexical environment in ecma 262 5
Lexical environment in ecma 262 5Kim Hunmin
 
Arduino coding class part ii
Arduino coding class part iiArduino coding class part ii
Arduino coding class part iiJonah Marrs
 
스위프트를 여행하는 히치하이커를 위한 스타일 안내
스위프트를 여행하는 히치하이커를 위한 스타일 안내스위프트를 여행하는 히치하이커를 위한 스타일 안내
스위프트를 여행하는 히치하이커를 위한 스타일 안내Jung Kim
 
NativeBoost
NativeBoostNativeBoost
NativeBoostESUG
 
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...DevGAMM Conference
 

What's hot (20)

Stop Monkeys Fall
Stop Monkeys FallStop Monkeys Fall
Stop Monkeys Fall
 
3
33
3
 
連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」
 
Arduino coding class
Arduino coding classArduino coding class
Arduino coding class
 
Practical JavaScript Programming - Session 6/8
Practical JavaScript Programming - Session 6/8Practical JavaScript Programming - Session 6/8
Practical JavaScript Programming - Session 6/8
 
Binaries Are Not Only Output
Binaries Are Not Only OutputBinaries Are Not Only Output
Binaries Are Not Only Output
 
The mighty js_function
The mighty js_functionThe mighty js_function
The mighty js_function
 
Swiftの関数型っぽい部分
Swiftの関数型っぽい部分Swiftの関数型っぽい部分
Swiftの関数型っぽい部分
 
Hacking parse.y (RubyKansai38)
Hacking parse.y (RubyKansai38)Hacking parse.y (RubyKansai38)
Hacking parse.y (RubyKansai38)
 
HailDB: A NoSQL API Direct to InnoDB
HailDB: A NoSQL API Direct to InnoDBHailDB: A NoSQL API Direct to InnoDB
HailDB: A NoSQL API Direct to InnoDB
 
Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.
 
Алексей Кутумов, Coroutines everywhere
Алексей Кутумов, Coroutines everywhereАлексей Кутумов, Coroutines everywhere
Алексей Кутумов, Coroutines everywhere
 
Letswift18 워크숍#1 스위프트 클린코드와 코드리뷰
Letswift18 워크숍#1 스위프트 클린코드와 코드리뷰Letswift18 워크숍#1 스위프트 클린코드와 코드리뷰
Letswift18 워크숍#1 스위프트 클린코드와 코드리뷰
 
Lexical environment in ecma 262 5
Lexical environment in ecma 262 5Lexical environment in ecma 262 5
Lexical environment in ecma 262 5
 
Arduino coding class part ii
Arduino coding class part iiArduino coding class part ii
Arduino coding class part ii
 
스위프트를 여행하는 히치하이커를 위한 스타일 안내
스위프트를 여행하는 히치하이커를 위한 스타일 안내스위프트를 여행하는 히치하이커를 위한 스타일 안내
스위프트를 여행하는 히치하이커를 위한 스타일 안내
 
ES2015 workflows
ES2015 workflowsES2015 workflows
ES2015 workflows
 
NativeBoost
NativeBoostNativeBoost
NativeBoost
 
Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6
 
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
 

Similar to Message in a bottle

Create your own PHP extension, step by step - phpDay 2012 Verona
Create your own PHP extension, step by step - phpDay 2012 VeronaCreate your own PHP extension, step by step - phpDay 2012 Verona
Create your own PHP extension, step by step - phpDay 2012 VeronaPatrick Allaert
 
NYU hacknight, april 6, 2016
NYU hacknight, april 6, 2016NYU hacknight, april 6, 2016
NYU hacknight, april 6, 2016Mikhail Sosonkin
 
Chaincode Development 區塊鏈鏈碼開發
Chaincode Development 區塊鏈鏈碼開發Chaincode Development 區塊鏈鏈碼開發
Chaincode Development 區塊鏈鏈碼開發HO-HSUN LIN
 
Catch a spider monkey
Catch a spider monkeyCatch a spider monkey
Catch a spider monkeyChengHui Weng
 
Mongoskin - Guilin
Mongoskin - GuilinMongoskin - Guilin
Mongoskin - GuilinJackson Tian
 
How to Write Node.js Module
How to Write Node.js ModuleHow to Write Node.js Module
How to Write Node.js ModuleFred Chien
 
掀起 Swift 的面紗
掀起 Swift 的面紗掀起 Swift 的面紗
掀起 Swift 的面紗Pofat Tseng
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 
Improving Android Performance at Droidcon UK 2014
Improving Android Performance at Droidcon UK 2014Improving Android Performance at Droidcon UK 2014
Improving Android Performance at Droidcon UK 2014Raimon Ràfols
 
Ruby C extensions at the Ruby drink-up of Sophia, April 2012
Ruby C extensions at the Ruby drink-up of Sophia, April 2012Ruby C extensions at the Ruby drink-up of Sophia, April 2012
Ruby C extensions at the Ruby drink-up of Sophia, April 2012rivierarb
 
Part II: LLVM Intermediate Representation
Part II: LLVM Intermediate RepresentationPart II: LLVM Intermediate Representation
Part II: LLVM Intermediate RepresentationWei-Ren Chen
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...DroidConTLV
 
Александр Трищенко: PHP 7 Evolution
Александр Трищенко: PHP 7 EvolutionАлександр Трищенко: PHP 7 Evolution
Александр Трищенко: PHP 7 EvolutionOleg Poludnenko
 
From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)Night Sailer
 

Similar to Message in a bottle (20)

Ricky Bobby's World
Ricky Bobby's WorldRicky Bobby's World
Ricky Bobby's World
 
Live Updating Swift Code
Live Updating Swift CodeLive Updating Swift Code
Live Updating Swift Code
 
Marat-Slides
Marat-SlidesMarat-Slides
Marat-Slides
 
Create your own PHP extension, step by step - phpDay 2012 Verona
Create your own PHP extension, step by step - phpDay 2012 VeronaCreate your own PHP extension, step by step - phpDay 2012 Verona
Create your own PHP extension, step by step - phpDay 2012 Verona
 
Rust ⇋ JavaScript
Rust ⇋ JavaScriptRust ⇋ JavaScript
Rust ⇋ JavaScript
 
NYU hacknight, april 6, 2016
NYU hacknight, april 6, 2016NYU hacknight, april 6, 2016
NYU hacknight, april 6, 2016
 
Chaincode Development 區塊鏈鏈碼開發
Chaincode Development 區塊鏈鏈碼開發Chaincode Development 區塊鏈鏈碼開發
Chaincode Development 區塊鏈鏈碼開發
 
Catch a spider monkey
Catch a spider monkeyCatch a spider monkey
Catch a spider monkey
 
Profiling Ruby
Profiling RubyProfiling Ruby
Profiling Ruby
 
Mongoskin - Guilin
Mongoskin - GuilinMongoskin - Guilin
Mongoskin - Guilin
 
How to Write Node.js Module
How to Write Node.js ModuleHow to Write Node.js Module
How to Write Node.js Module
 
掀起 Swift 的面紗
掀起 Swift 的面紗掀起 Swift 的面紗
掀起 Swift 的面紗
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
Improving Android Performance at Droidcon UK 2014
Improving Android Performance at Droidcon UK 2014Improving Android Performance at Droidcon UK 2014
Improving Android Performance at Droidcon UK 2014
 
Ruby C extensions at the Ruby drink-up of Sophia, April 2012
Ruby C extensions at the Ruby drink-up of Sophia, April 2012Ruby C extensions at the Ruby drink-up of Sophia, April 2012
Ruby C extensions at the Ruby drink-up of Sophia, April 2012
 
Part II: LLVM Intermediate Representation
Part II: LLVM Intermediate RepresentationPart II: LLVM Intermediate Representation
Part II: LLVM Intermediate Representation
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
 
Александр Трищенко: PHP 7 Evolution
Александр Трищенко: PHP 7 EvolutionАлександр Трищенко: PHP 7 Evolution
Александр Трищенко: PHP 7 Evolution
 
From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)
 

Recently uploaded

AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAnitaRaj43
 
API Governance and Monetization - The evolution of API governance
API Governance and Monetization -  The evolution of API governanceAPI Governance and Monetization -  The evolution of API governance
API Governance and Monetization - The evolution of API governanceWSO2
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard37
 
Choreo: Empowering the Future of Enterprise Software Engineering
Choreo: Empowering the Future of Enterprise Software EngineeringChoreo: Empowering the Future of Enterprise Software Engineering
Choreo: Empowering the Future of Enterprise Software EngineeringWSO2
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Quantum Leap in Next-Generation Computing
Quantum Leap in Next-Generation ComputingQuantum Leap in Next-Generation Computing
Quantum Leap in Next-Generation ComputingWSO2
 
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....rightmanforbloodline
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Less Is More: Utilizing Ballerina to Architect a Cloud Data Platform
Less Is More: Utilizing Ballerina to Architect a Cloud Data PlatformLess Is More: Utilizing Ballerina to Architect a Cloud Data Platform
Less Is More: Utilizing Ballerina to Architect a Cloud Data PlatformWSO2
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...caitlingebhard1
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 

Recently uploaded (20)

AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
API Governance and Monetization - The evolution of API governance
API Governance and Monetization -  The evolution of API governanceAPI Governance and Monetization -  The evolution of API governance
API Governance and Monetization - The evolution of API governance
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptx
 
Choreo: Empowering the Future of Enterprise Software Engineering
Choreo: Empowering the Future of Enterprise Software EngineeringChoreo: Empowering the Future of Enterprise Software Engineering
Choreo: Empowering the Future of Enterprise Software Engineering
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Quantum Leap in Next-Generation Computing
Quantum Leap in Next-Generation ComputingQuantum Leap in Next-Generation Computing
Quantum Leap in Next-Generation Computing
 
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Less Is More: Utilizing Ballerina to Architect a Cloud Data Platform
Less Is More: Utilizing Ballerina to Architect a Cloud Data PlatformLess Is More: Utilizing Ballerina to Architect a Cloud Data Platform
Less Is More: Utilizing Ballerina to Architect a Cloud Data Platform
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 

Message in a bottle

  • 1. Message In A Bottle Konstantin Haase
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9. Ruby 1.8 is slow because it's interpreted. Surprise! Ruby 1.9 is interpreted, too.
  • 10. Thanks! github.com / rkh / presentations
  • 11. Ruby
  • 12.
  • 13.
  • 14.
  • 15. What We'll Look Into MRI: method dispatch and execution Rubinius: inline caches and JIT JRuby: invokedynamic
  • 16.
  • 17.
  • 18. class DeepThought def ultimate_answer?(value) value.to_s == '42' end end DeepThought.new.ultimate_answer? 42
  • 19. They Just Love Bytecode Ruby value.to_s MRI getlocal value send :to_s, 0, nil, 0, <ic:0> Rubinius push_local 0 send_stack :to_s, 0 JRuby ALOAD 0 LDC "to_suffffNuffffu0000u0000u0001u0000u0000u0000u0000u0000u0000... INVOKEVIRTUAL org/jruby/ast/executable/AbstractScript.initFromDescriptor (Lj... ... ALOAD 0 INVOKEVIRTUAL ruby/__dash_e__.getCallSite0 ()Lorg/jruby/runtime/CallSite; ALOAD 1 ALOAD 2 ALOAD 9 INVOKEVIRTUAL org/jruby/runtime/CallSite.call (Lorg/jruby/runtime/ThreadCont...
  • 20. The Plan search for method execute method
  • 21.
  • 22. How To Speed That Up? search faster execute faster
  • 23. Speed Up Search Inline Cache (aka Call/Send Site Cache) Lookup Cache Inlining
  • 24. Speed Up Execution Reduce operations Just-in-time compilation Inlining Speed up search
  • 25. MRI
  • 26. a method gets called rb_call0
  • 27. static inline VALUE rb_call0(VALUE recv, ID mid, int argc, const VALUE *argv, call_type scope, VALUE self) { rb_method_entry_t *me = rb_search_method_entry(recv, mid); rb_thread_t *th = GET_THREAD(); int call_status = rb_method_call_status(th, me, scope, self); // <- SEARCH if (call_status != NOEX_OK) { return method_missing(recv, mid, argc, argv, call_status); } stack_check(); return vm_call0(th, recv, mid, argc, argv, me); // <- EXECUTE }
  • 28.
  • 29. /* * rb_call0 searching for a method * -> rb_method_entry * -> rb_method_entry_get_without_cache * -> search_method */ static rb_method_entry_t* search_method(VALUE klass, ID id) { st_data_t body; if (!klass) { return 0; } while (!st_lookup(RCLASS_M_TBL(klass), id, &body)) { klass = RCLASS_SUPER(klass); if (!klass) { return 0; } } return (rb_method_entry_t *)body; }
  • 30.
  • 31. /* * rb_call0 executing a method * -> vm_call0 */ static inline VALUE vm_call0(rb_thread_t* th, VALUE recv, VALUE id, int argc, const VALUE *argv, const rb_method_entry_t *me) { const rb_method_definition_t *def = me->def; VALUE val; const rb_block_t *blockptr = 0; // ... again: switch (def->type) { case VM_METHOD_TYPE_ISEQ: { rb_control_frame_t *reg_cfp; // ... vm_setup_method(th, reg_cfp, recv, argc, blockptr, 0 /* flag */, me); val = vm_exec(th); // <- EXECUTE !!! break; } // ... } // ... }
  • 32. static VALUE vm_exec(rb_thread_t *th) { // ... go see for yourself ... }
  • 33.
  • 34. DEFINE_INSN send (ID op_id, rb_num_t op_argc, ISEQ blockiseq, rb_num_t op_flag, IC ic) (...) (VALUE val) // inc += - (int)(op_argc + ((op_flag & VM_CALL_ARGS_BLOCKARG_BIT) ? 1 : 0)); { const rb_method_entry_t *me; VALUE recv, klass; rb_block_t *blockptr = 0; VALUE flag = op_flag; int num = caller_setup_args(th, GET_CFP(), flag, (int)op_argc, (rb_iseq_t *)blockiseq, &blockptr); ID id = op_id; /* get receiver */ recv = (flag & VM_CALL_FCALL_BIT) ? GET_SELF() : TOPN(num); klass = CLASS_OF(recv); me = vm_method_search(id, klass, ic); CALL_METHOD(num, blockptr, flag, id, me, recv); }
  • 36.
  • 37. klass = object.singleton_class method = nil while klass and not method method = klass.method_table.lookup(:some_method) klass = klass.direct_superclass end
  • 38. >> cm = DeepThought.method_table ?> .lookup(:ultimate_answer?).method => #<Rubinius::CompiledMethod ultimate_answer?> >> puts cm.decode 0000: push_local 0 # value 0002: send_stack :to_s, 0 0005: push_literal "42" 0007: string_dup 0008: meta_send_op_equal :== 0010: ret => nil >> cm.iseq.opcodes => #<Rubinius::Tuple: 20, 0, 49, 0, 0, 7, 1, 64, 83, 2, 11> >> cm.literals => #<Rubinius::Tuple: :to_s, "42", :==>
  • 39. literals: :to_s, "42", :== locals: value (42) bytes: 20 0 49 0 0 7 1 64 83 2 11 bytes decoded stack 20 0 push_local 0 [ 42 ] 49 0 0 send_stack :to_s, 0 [ "42" ] 7 1 push_literal "42" [ "42", "42" ] 64 string_dup [ "42", "42" ] 83 2 meta_send_op_equal [ true ] 11 ret [ ]
  • 40.
  • 41. instruction send_stack(literal count) [ receiver +count -- value ] => send Object* recv = stack_back(count); InlineCache* cache = reinterpret_cast<InlineCache*>(literal); Arguments args(cache->name, recv, Qnil, count, stack_back_position(count)); Object* ret = cache->execute(state, call_frame, args); CHECK_AND_PUSH(ret); end
  • 42.
  • 43.
  • 44. Specialized Methods cached bytecode code with breakpoints specialized for arguments JITed code
  • 45.
  • 46. JRuby
  • 47.
  • 48. INVOKEVIRTUAL INVOKEVIRTUAL example.getCallSite1 ... ALOAD 1 ALOAD 2 ALOAD 9 INVOKEVIRTUAL org/jruby/runtime/CallSite.call ... INVOKEDYNAMIC ALOAD 1 ALOAD 2 ALOAD 9 INVOKEDYNAMIC call ...
  • 49. INVOKEVIRTUAL INVOKEVIRTUAL org/jruby/runtime/CallSite.call( Lorg/jruby/runtime/ThreadContext; Lorg/jruby/runtime/builtin/IRubyObject; Lorg/jruby/runtime/builtin/IRubyObject; )Lorg/jruby/runtime/builtin/IRubyObject; INVOKEDYNAMIC INVOKEDYNAMIC call( Lorg/jruby/runtime/ThreadContext; Lorg/jruby/runtime/builtin/IRubyObject; Lorg/jruby/runtime/builtin/IRubyObject; Ljava/lang/String; )Lorg/jruby/runtime/builtin/IRubyObject; [...]
  • 50. The Linker [org/jruby/runtime/invokedynamic/InvocationLinker .invocationBootstrap( Ljava/lang/invoke/MethodHandles$Lookup; Ljava/lang/String; Ljava/lang/invoke/MethodType; )Ljava/lang/invoke/CallSite;]
  • 51.
  • 52. The Bootstrap public static CallSite invocationBootstrap(Lookup lookup, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { CallSite site; // ... if (name.equals("call")) { site = new JRubyCallSite(lookup, type, CallType.NORMAL, false, false, true); } // ... MethodHandle myFallback = ... site.setTarget(myFallback); return site; }
  • 53.
  • 54. The Fallback public static IRubyObject invocationFallback(JRubyCallSite site, ThreadContext context, IRubyObject caller, IRubyObject self, String name) throws Throwable { RubyClass selfClass = pollAndGetClass(context, self); CacheEntry entry = selfClass.searchWithCache(name); if (methodMissing(entry, site.callType(), name, caller)) { return callMethodMissing(entry, site.callType(), context, self, name); } MethodHandle target = getTarget(site, selfClass, name, entry, 0); target = updateInvocationTarget(target, site, selfClass, name, entry, false, 0); return (IRubyObject)target.invokeWithArguments(context, caller, self, name); }
  • 55. images http://kosmur.deviantart.com/art/assembler-79007314 https://www.facebook.com/headius https://www.facebook.com/koichi.sasada https://www.facebook.com/profile.php?id=523826914 http://farm4.static.flickr.com/3207/2522976901_6ff55314cd.jpg http://www.flickr.com/photos/binkley27/3451700024 http://www.flickr.com/photos/funtik/1175522045 http://en.wikipedia.org/wiki/File:Answer_to_Life.png http://www.flickr.com/photos/makelessnoise/195088755/ http://www.flickr.com/photos/jeffhenshaw/4833007463/ http://churchmusictoday.wordpress.com/2011/05/13/ten-warning-signs-for-churches-from-thom-ranier/ http://www.freefoto.com/preview/28-06-3/Police-Underwater-Search-Unit http://blog-blond.blogspot.com/2009/07/how-to-do-blogs-right.html http://fuckyouverymuch.dk/post/9661487809/we-are-ready-to-leave http://crunchtools.com/bootstrapping-and-rooting-documentation-part-2/ http://www.softmyhard.com/tag/device-instruction-manual http://www.flickr.com/photos/quinnanya/4874581964
  • 56. Thanks! github.com / rkh / presentations