SlideShare a Scribd company logo
1 of 47
What lies beneath
  the beautiful
      code?



     Ruby Conf India 2012
Ruby Conf India 2012
self.inspect

{

:name => “Niranjan Sarade”,

:role   => “ruby developer @ TCS”,

:blog   => “http://niranjansarade.blogspot.com”

:tweet => “twitter.com/nirusuma”,

:github => “github.com/NiranjanSarade”

}



                         Ruby Conf India 2012
Ruby Conf India 2012
Ruby


      Beautiful


Pure object oriented


    Interpreted




     Ruby Conf India 2012
Matz’s Ruby Interpreter (MRI)




 Koichi’s Ruby Interpreter (KRI)

        Ruby Conf India 2012
Why
  should
    we
  know?




Ruby Conf India 2012
Let’s dive in!




  Ruby Conf India 2012
Why C?




Ruby Conf India 2012
TPI Ruby 1.8

 Ruby
source
         Tokenize
 code     (yylex)



                            Parse
         Series of tokens   (yacc)




                                                   Interpret
                                      AST




                            Ruby Conf India 2012
TPCI Ruby 1.9

 Ruby
source
         Tokenize
 code     (yylex)



                             Parse
         Series of tokens   (Bison)




                                                     Compile
                                      AST          (compile.c)




                                                                     Interpret
                                                          bytecode    (YARV)
                            Ruby Conf India 2012
Tokenized




                       Parsed (AST)




  bytecode




Ruby Conf India 2012
Tokenized




                       Parsed (AST)




    bytecode




Ruby Conf India 2012
Ruby Source Overview

# README.EXT

ruby language core

    class.c       : classes and modules
    error.c      : exception classes and exception mechanism
    gc.c         : memory management
    load.c       : library loading
    object.c     : objects
    variable.c   : variables and constants

ruby syntax parser
    parse.y
      -> parse.c : automatically generated
    keywords     : reserved keywords
      -> lex.c   : automatically generated




                                Ruby Conf India 2012
ruby evaluator (a.k.a. YARV)

    compile.c
    eval.c
    eval_error.c
    eval_jump.c
    eval_safe.c
    insns.def      : definition of VM instructions
    iseq.c         : implementation of VM::ISeq
    thread.c       : thread management and context swiching
    thread_win32.c : thread implementation
    thread_pthread.c : ditto
    vm.c
    vm_dump.c
    vm_eval.c
    vm_exec.c
    vm_insnhelper.c
    vm_method.c



                               Ruby Conf India 2012
regular expression engine (oniguruma)
    regex.c
    regcomp.c
    regenc.c
    regerror.c
    regexec.c
    regparse.c
    regsyntax.c


utility functions
      debug.c     : debug symbols for C debuggger
      dln.c       : dynamic loading
      st.c        : general purpose hash table
      strftime.c : formatting times
      util.c      : misc utilities




                                 Ruby Conf India 2012
ruby interpreter implementation

    dmyext.c
    dmydln.c
    dmyencoding.c
    id.c
    inits.c
    main.c
    ruby.c
    version.c

multilingualization
     encoding.c : Encoding
     transcode.c : Encoding::Converter
     enc/*.c      : encoding classes
     enc/trans/* : codepoint mapping tables




                                  Ruby Conf India 2012
class library

    array.c      : Array                       numeric.c    : Numeric, Integer, Fixnum,
    bignum.c     : Bignum
    compar.c     : Comparable                                   Float
    complex.c     : Complex                    pack.c       : Array#pack, String#unpack
    cont.c       : Fiber, Continuation         proc.c       : Binding, Proc
    dir.c        : Dir                         process.c     : Process
    enum.c       : Enumerable                  random.c      : random number
    enumerator.c : Enumerator                  range.c       : Range
    file.c      : File                         rational.c     : Rational
    hash.c       : Hash                        re.c          : Regexp, MatchData
    io.c         : IO                          signal.c      : Signal
    marshal.c    : Marshal                     sprintf.c    :
    math.c       : Math                        string.c     : String
                                               struct.c     : Struct
                                               time.c       : Time




                                 Ruby Conf India 2012
ruby.h


Struct Rbasic                           Struct RRegexp

Struct RObject                          Struct RHash

Struct RClass                           Struct RFile

Struct RFloat                           Struct RBignum

Struct RString                          Struct RArray




                 Ruby Conf India 2012
RObject, RBasic and RClass


struct RObject {                                    struct RClass {
   struct RBasic basic;                                struct RBasic basic;
   union {                                             rb_classext_t *ptr;
           struct {                                    struct st_table *m_tbl;
              long numiv;                              struct st_table *iv_index_tbl;
              VALUE *ivptr;                         };
              struct st_table *iv_index_tbl;
           } heap;
    } as;
};

struct RBasic {
   VALUE flags;
   VALUE klass;
};




                                     Ruby Conf India 2012
Instance specific behavior

my_obj = Object.new


def my_obj.hello
      p “hello”
end


my_obj.hello
#=> hello


Object.new.hello

# NoMethodError: # undefined method `hello' for #<Object:0x5418467>




                              Ruby Conf India 2012
Conceptual sketch



                               Object
my_obj
    klass                      *m_tbl



                               Object
                               *m_tbl



                               ‘my_obj
my_obj                               *super
    klass                      *m_tbl
                                 -hello



            Ruby Conf India 2012
#class.c
VALUE
   make_singleton_class(VALUE obj)
   {
     VALUE orig_class = RBASIC(obj)->klass;
     VALUE klass = rb_class_boot(orig_class);

       FL_SET(klass, FL_SINGLETON);
       RBASIC(obj)->klass = klass;

       return klass;
   }




                       Ruby Conf India 2012
Am I Immediate Object or Pointer ?




              VALUE




            Ruby Conf India 2012
typedef unsigned long VALUE


   C type for referring to arbitrary ruby objects

Stores immediate values of :-
   Fixnum
   Symbols
   True
   False
   Nil
   Undef


Bit test :
   If the LSB = 1, it is a Fixnum.

   If the VALUE is equal to 0,2,4, or 6 it is a special constant:
   false, true, nil, or undef.

   If the lower 8 bits are equal to '0xe', it is a Symbol.

   Otherwise, it is an Object Reference
                               Ruby Conf India 2012
RString


#1.8.7                        # 1.9.3
struct RString {              #define RSTRING_EMBED_LEN_MAX ((int)
   struct RBasic basic;       ((sizeof(VALUE)*3)/sizeof(char)-1))
   long len;                  struct RString {
   char *ptr;                    struct RBasic basic;
   union {                       union {
   long capa;                    struct {
   VALUE shared;                    long len;
   } aux;                           char *ptr;
};                                  union {
                                    long capa;
                                    VALUE shared;
                                    } aux;
                                 } heap;
                                 char ary[RSTRING_EMBED_LEN_MAX + 1];
                                 } as;
                              };


                          Ruby Conf India 2012
Ruby Conf India 2012
Images created using wordle.net
Heap Strings


                                               Heap
 str

       RString

        char *ptr                                 “This is a very very very
       long len = 46                                very very long string”




str2




                        Ruby Conf India 2012
Ruby Conf India 2012
Ruby Conf India 2012
Shared Strings
       str = "This is a very very very very very long string"
       str2 = String.new(str)
       #str2 = str.dup


                                               Heap
          RString
          char *ptr
str2
         long len = 46
       VALUE shared


                                                   “This is a very very very
                                                     very very long string”


          RString

str       char *ptr
         long len = 46



                            Ruby Conf India 2012
Ruby Conf India 2012
Copy on Write

       str = "This is a very very very very very long string"
       str2 = str.dup
       str2.upcase!


                                                   Heap
          RString
str       char *ptr
                                                   “This is a very very very very very
                                                   long string”
         long len = 46




          RString
                                                   “THIS IS A VERY VERY VERY
str2      char *ptr                                VERY VERY LONG STRING”
         long len = 46


                            Ruby Conf India 2012
Ruby Conf India 2012
Embedded Strings

        str = "This is a very very very very very long string"
        str2 = str[0..3]
        #str2 = “This”


                                                    Heap
            RString
str         char *ptr
                                                    “This is a very very very very very
                                                    long string”
           long len = 46




            Rstring

str2      long len = 4
       char ary[] = “This”

                             Ruby Conf India 2012
Ruby Conf India 2012
Shared Strings with slice

       str = "This is a very very very very very long string"
       str2 = str[1..-1]
       #str2 = str[22..-1]
       # 0 <= start_offset < 46-23



          RString
                                              Heap

str       char *ptr
         long len = 46
       VALUE shared
                                                  T   h   i   .   .   i   n   g




          RString

str2      char *ptr
         long len = 45

                           Ruby Conf India 2012
Ruby Conf India 2012
String.new(“learning”)

Creating a string 23 characters or less is fastest


Creating a substring running to the end of the target string is also fast


When sharing same string data, memory and execution time is saved


Creating any other long substring or string, 24 or more bytes, is slower.




                                Ruby Conf India 2012
RHash
                            1.8.7 :002 > {1 => "a", "f" => "b", 2 => "c"}
                            => {1=>"a", 2=>"c", "f"=>"b"}

                            1.9.3p0 :001 > {1 => "a", "f" => "b", 2 => "c"}
                            => {1=>"a", "f"=>"b", 2=>"c"}

#1.8.7                                                     #1.9.3
struct RHash {                                             struct RHash {
   struct RBasic basic;                                       struct RBasic basic;
   struct st_table *tbl;                                      struct st_table *ntbl;
   int iter_lev;                                              int iter_lev;
   VALUE ifnone;                                              VALUE ifnone;
};                                                         };

struct st_table {                                          struct st_table {
   struct st_hash_type *type;                                 const struct st_hash_type *type;
   int num_bins;                                              st_index_t num_bins;
   int num_entries;                                           ...
   struct st_table_entry **bins;                              struct st_table_entry **bins;
};                                                            struct st_table_entry *head, *tail;
                                                           };
struct st_table_entry {                                    struct st_table_entry {
   st_data_t key;                                             st_data_t key;
   st_data_t record;                                          st_data_t record;
   st_table_entry *next;                                      st_table_entry *next;
};                                                            st_table_entry *fore, *back;
                                                           };
                                            Ruby Conf India 2012
RHash 1.8.7
                                                        st_table_entries


                                         key1   value                key3   value   x



  st_table
                                         key2   value            x
num_entries = 4

num_bins = 5

  **bins




                                         key4   value            x




                  hash buckets - slots




                                  Ruby Conf India 2012
RHash 1.9.3
                                                      st_table_entries


                               1x          key1    value                 key2   value   3
                               4x                                                       2


  st_table
                                3          key3    value          4
                                2                                 3
num_entries = 4

num_bins = 5

   **bins

*head

*tail

                               4           key4    value         1x
                               3                                 4x




                  hash buckets - slots




                                    Ruby Conf India 2012
Ruby Conf India 2012
C Extensions – why and when ?

Performance

Using C libraries from ruby applications

Using ruby gems with native C extensions

e.g. mysql, nokogiri, eventmachine, RedCloth, Rmagick, libxml-ruby, etc

Since ruby interpreter is implemented in C, its API can be used




                               Ruby Conf India 2012
My fellow                ist
Patrick Shaughnessy




    Ruby Conf India 2012
Image Credits

http://pguims-random-science.blogspot.in/2011/08/ten-benefits-of-scuba-diving.html

http://www.istockphoto.com/stock-illustration-7620122-tree-roots.php

http://horror.about.com/od/horrortoppicklists/tp/familyfriendlyhorror.01.htm

http://www.creditwritedowns.com/2011/07/european-monetary-union-titanic.html

http://irvine-orthodontist.com/wordpress/for-new-patients/faqs




                                      Ruby Conf India 2012
Thank you all for being patient
    and hearing me out !

    Hope this helps you !




          Ruby Conf India 2012

More Related Content

Viewers also liked

Vi Nguyen's Waves of Grace Presentation
Vi Nguyen's Waves of Grace PresentationVi Nguyen's Waves of Grace Presentation
Vi Nguyen's Waves of Grace Presentationvi_was_here
 
Summative Presentation
Summative PresentationSummative Presentation
Summative Presentationmontie1989
 
Monografía david velas
Monografía david velasMonografía david velas
Monografía david velasdavid velasco
 
Technology nicole
Technology nicoleTechnology nicole
Technology nicoleNICKYDAVIS
 
Referencias Bibliograficas con normas APA
Referencias Bibliograficas con normas APAReferencias Bibliograficas con normas APA
Referencias Bibliograficas con normas APALola Costa
 
Actividad 5.1 Aprendizaje
Actividad 5.1 AprendizajeActividad 5.1 Aprendizaje
Actividad 5.1 Aprendizajefredy purizaca
 
збери сам ферма
збери сам фермазбери сам ферма
збери сам фермаAnna Polud
 
Dan Bannino
Dan BanninoDan Bannino
Dan BanninoAOtaki
 

Viewers also liked (12)

Tο τείχος του βερολίνου
Tο τείχος του βερολίνουTο τείχος του βερολίνου
Tο τείχος του βερολίνου
 
Framework
FrameworkFramework
Framework
 
Vi Nguyen's Waves of Grace Presentation
Vi Nguyen's Waves of Grace PresentationVi Nguyen's Waves of Grace Presentation
Vi Nguyen's Waves of Grace Presentation
 
Summative Presentation
Summative PresentationSummative Presentation
Summative Presentation
 
Monografía david velas
Monografía david velasMonografía david velas
Monografía david velas
 
Technology nicole
Technology nicoleTechnology nicole
Technology nicole
 
Referencias Bibliograficas con normas APA
Referencias Bibliograficas con normas APAReferencias Bibliograficas con normas APA
Referencias Bibliograficas con normas APA
 
Jmeter
JmeterJmeter
Jmeter
 
Hackathon6
Hackathon6Hackathon6
Hackathon6
 
Actividad 5.1 Aprendizaje
Actividad 5.1 AprendizajeActividad 5.1 Aprendizaje
Actividad 5.1 Aprendizaje
 
збери сам ферма
збери сам фермазбери сам ферма
збери сам ферма
 
Dan Bannino
Dan BanninoDan Bannino
Dan Bannino
 

Similar to What lies beneath the beautiful code

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
 
Mac ruby deployment
Mac ruby deploymentMac ruby deployment
Mac ruby deploymentThilo Utke
 
Ruby On Rails Overview
Ruby On Rails OverviewRuby On Rails Overview
Ruby On Rails Overviewjonkinney
 
The details of CI/CD environment for Ruby
The details of CI/CD environment for RubyThe details of CI/CD environment for Ruby
The details of CI/CD environment for RubyHiroshi SHIBATA
 
MacRuby & HotCocoa
MacRuby & HotCocoaMacRuby & HotCocoa
MacRuby & HotCocoaThilo Utke
 
What's new in Ruby 2.0
What's new in Ruby 2.0What's new in Ruby 2.0
What's new in Ruby 2.0Kartik Sahoo
 
A bridge between php and ruby
A bridge between php and ruby A bridge between php and ruby
A bridge between php and ruby do_aki
 
Introduction to Ruby on Rails
Introduction to Ruby on RailsIntroduction to Ruby on Rails
Introduction to Ruby on RailsManoj Kumar
 
Ruby on Rails survival guide of an aged Java developer
Ruby on Rails survival guide of an aged Java developerRuby on Rails survival guide of an aged Java developer
Ruby on Rails survival guide of an aged Java developergicappa
 
Extending Ruby using C++
Extending Ruby using C++Extending Ruby using C++
Extending Ruby using C++Tristan Penman
 
Rspec and Capybara Intro Tutorial at RailsConf 2013
Rspec and Capybara Intro Tutorial at RailsConf 2013Rspec and Capybara Intro Tutorial at RailsConf 2013
Rspec and Capybara Intro Tutorial at RailsConf 2013Brian Sam-Bodden
 
JRuby - Programmer's Best Friend on JVM
JRuby - Programmer's Best Friend on JVMJRuby - Programmer's Best Friend on JVM
JRuby - Programmer's Best Friend on JVMRaimonds Simanovskis
 
Ruby for C#-ers (ScanDevConf 2010)
Ruby for C#-ers (ScanDevConf 2010)Ruby for C#-ers (ScanDevConf 2010)
Ruby for C#-ers (ScanDevConf 2010)Thomas Lundström
 
Auto cad 2006_api_overview
Auto cad 2006_api_overviewAuto cad 2006_api_overview
Auto cad 2006_api_overviewscdhruv5
 

Similar to What lies beneath the beautiful code (20)

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
 
RubyMotion Introduction
RubyMotion IntroductionRubyMotion Introduction
RubyMotion Introduction
 
Mac ruby deployment
Mac ruby deploymentMac ruby deployment
Mac ruby deployment
 
Ruby On Rails Overview
Ruby On Rails OverviewRuby On Rails Overview
Ruby On Rails Overview
 
The details of CI/CD environment for Ruby
The details of CI/CD environment for RubyThe details of CI/CD environment for Ruby
The details of CI/CD environment for Ruby
 
MacRuby & HotCocoa
MacRuby & HotCocoaMacRuby & HotCocoa
MacRuby & HotCocoa
 
What's new in Ruby 2.0
What's new in Ruby 2.0What's new in Ruby 2.0
What's new in Ruby 2.0
 
A bridge between php and ruby
A bridge between php and ruby A bridge between php and ruby
A bridge between php and ruby
 
Introduction to Ruby on Rails
Introduction to Ruby on RailsIntroduction to Ruby on Rails
Introduction to Ruby on Rails
 
Ruby on Rails survival guide of an aged Java developer
Ruby on Rails survival guide of an aged Java developerRuby on Rails survival guide of an aged Java developer
Ruby on Rails survival guide of an aged Java developer
 
Opal compiler
Opal compilerOpal compiler
Opal compiler
 
How to write Ruby extensions with Crystal
How to write Ruby extensions with CrystalHow to write Ruby extensions with Crystal
How to write Ruby extensions with Crystal
 
Intro to J Ruby
Intro to J RubyIntro to J Ruby
Intro to J Ruby
 
Rsltollvm
RsltollvmRsltollvm
Rsltollvm
 
Extending Ruby using C++
Extending Ruby using C++Extending Ruby using C++
Extending Ruby using C++
 
Rspec and Capybara Intro Tutorial at RailsConf 2013
Rspec and Capybara Intro Tutorial at RailsConf 2013Rspec and Capybara Intro Tutorial at RailsConf 2013
Rspec and Capybara Intro Tutorial at RailsConf 2013
 
JRuby - Programmer's Best Friend on JVM
JRuby - Programmer's Best Friend on JVMJRuby - Programmer's Best Friend on JVM
JRuby - Programmer's Best Friend on JVM
 
Ruby for C#-ers (ScanDevConf 2010)
Ruby for C#-ers (ScanDevConf 2010)Ruby for C#-ers (ScanDevConf 2010)
Ruby for C#-ers (ScanDevConf 2010)
 
Auto cad 2006_api_overview
Auto cad 2006_api_overviewAuto cad 2006_api_overview
Auto cad 2006_api_overview
 
Ruby on rails
Ruby on railsRuby on rails
Ruby on rails
 

Recently uploaded

Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 

Recently uploaded (20)

Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 

What lies beneath the beautiful code

  • 1. What lies beneath the beautiful code? Ruby Conf India 2012
  • 3. self.inspect { :name => “Niranjan Sarade”, :role => “ruby developer @ TCS”, :blog => “http://niranjansarade.blogspot.com” :tweet => “twitter.com/nirusuma”, :github => “github.com/NiranjanSarade” } Ruby Conf India 2012
  • 5. Ruby Beautiful Pure object oriented Interpreted Ruby Conf India 2012
  • 6. Matz’s Ruby Interpreter (MRI) Koichi’s Ruby Interpreter (KRI) Ruby Conf India 2012
  • 7. Why should we know? Ruby Conf India 2012
  • 8. Let’s dive in! Ruby Conf India 2012
  • 9. Why C? Ruby Conf India 2012
  • 10. TPI Ruby 1.8 Ruby source Tokenize code (yylex) Parse Series of tokens (yacc) Interpret AST Ruby Conf India 2012
  • 11. TPCI Ruby 1.9 Ruby source Tokenize code (yylex) Parse Series of tokens (Bison) Compile AST (compile.c) Interpret bytecode (YARV) Ruby Conf India 2012
  • 12. Tokenized Parsed (AST) bytecode Ruby Conf India 2012
  • 13. Tokenized Parsed (AST) bytecode Ruby Conf India 2012
  • 14. Ruby Source Overview # README.EXT ruby language core class.c : classes and modules error.c : exception classes and exception mechanism gc.c : memory management load.c : library loading object.c : objects variable.c : variables and constants ruby syntax parser parse.y -> parse.c : automatically generated keywords : reserved keywords -> lex.c : automatically generated Ruby Conf India 2012
  • 15. ruby evaluator (a.k.a. YARV) compile.c eval.c eval_error.c eval_jump.c eval_safe.c insns.def : definition of VM instructions iseq.c : implementation of VM::ISeq thread.c : thread management and context swiching thread_win32.c : thread implementation thread_pthread.c : ditto vm.c vm_dump.c vm_eval.c vm_exec.c vm_insnhelper.c vm_method.c Ruby Conf India 2012
  • 16. regular expression engine (oniguruma) regex.c regcomp.c regenc.c regerror.c regexec.c regparse.c regsyntax.c utility functions debug.c : debug symbols for C debuggger dln.c : dynamic loading st.c : general purpose hash table strftime.c : formatting times util.c : misc utilities Ruby Conf India 2012
  • 17. ruby interpreter implementation dmyext.c dmydln.c dmyencoding.c id.c inits.c main.c ruby.c version.c multilingualization encoding.c : Encoding transcode.c : Encoding::Converter enc/*.c : encoding classes enc/trans/* : codepoint mapping tables Ruby Conf India 2012
  • 18. class library array.c : Array numeric.c : Numeric, Integer, Fixnum, bignum.c : Bignum compar.c : Comparable Float complex.c : Complex pack.c : Array#pack, String#unpack cont.c : Fiber, Continuation proc.c : Binding, Proc dir.c : Dir process.c : Process enum.c : Enumerable random.c : random number enumerator.c : Enumerator range.c : Range file.c : File rational.c : Rational hash.c : Hash re.c : Regexp, MatchData io.c : IO signal.c : Signal marshal.c : Marshal sprintf.c : math.c : Math string.c : String struct.c : Struct time.c : Time Ruby Conf India 2012
  • 19. ruby.h Struct Rbasic Struct RRegexp Struct RObject Struct RHash Struct RClass Struct RFile Struct RFloat Struct RBignum Struct RString Struct RArray Ruby Conf India 2012
  • 20. RObject, RBasic and RClass struct RObject { struct RClass { struct RBasic basic; struct RBasic basic; union { rb_classext_t *ptr; struct { struct st_table *m_tbl; long numiv; struct st_table *iv_index_tbl; VALUE *ivptr; }; struct st_table *iv_index_tbl; } heap; } as; }; struct RBasic { VALUE flags; VALUE klass; }; Ruby Conf India 2012
  • 21. Instance specific behavior my_obj = Object.new def my_obj.hello p “hello” end my_obj.hello #=> hello Object.new.hello # NoMethodError: # undefined method `hello' for #<Object:0x5418467> Ruby Conf India 2012
  • 22. Conceptual sketch Object my_obj klass *m_tbl Object *m_tbl ‘my_obj my_obj *super klass *m_tbl -hello Ruby Conf India 2012
  • 23. #class.c VALUE make_singleton_class(VALUE obj) { VALUE orig_class = RBASIC(obj)->klass; VALUE klass = rb_class_boot(orig_class); FL_SET(klass, FL_SINGLETON); RBASIC(obj)->klass = klass; return klass; } Ruby Conf India 2012
  • 24. Am I Immediate Object or Pointer ? VALUE Ruby Conf India 2012
  • 25. typedef unsigned long VALUE C type for referring to arbitrary ruby objects Stores immediate values of :- Fixnum Symbols True False Nil Undef Bit test : If the LSB = 1, it is a Fixnum. If the VALUE is equal to 0,2,4, or 6 it is a special constant: false, true, nil, or undef. If the lower 8 bits are equal to '0xe', it is a Symbol. Otherwise, it is an Object Reference Ruby Conf India 2012
  • 26. RString #1.8.7 # 1.9.3 struct RString { #define RSTRING_EMBED_LEN_MAX ((int) struct RBasic basic; ((sizeof(VALUE)*3)/sizeof(char)-1)) long len; struct RString { char *ptr; struct RBasic basic; union { union { long capa; struct { VALUE shared; long len; } aux; char *ptr; }; union { long capa; VALUE shared; } aux; } heap; char ary[RSTRING_EMBED_LEN_MAX + 1]; } as; }; Ruby Conf India 2012
  • 27. Ruby Conf India 2012 Images created using wordle.net
  • 28. Heap Strings Heap str RString char *ptr “This is a very very very long len = 46 very very long string” str2 Ruby Conf India 2012
  • 31. Shared Strings str = "This is a very very very very very long string" str2 = String.new(str) #str2 = str.dup Heap RString char *ptr str2 long len = 46 VALUE shared “This is a very very very very very long string” RString str char *ptr long len = 46 Ruby Conf India 2012
  • 33. Copy on Write str = "This is a very very very very very long string" str2 = str.dup str2.upcase! Heap RString str char *ptr “This is a very very very very very long string” long len = 46 RString “THIS IS A VERY VERY VERY str2 char *ptr VERY VERY LONG STRING” long len = 46 Ruby Conf India 2012
  • 35. Embedded Strings str = "This is a very very very very very long string" str2 = str[0..3] #str2 = “This” Heap RString str char *ptr “This is a very very very very very long string” long len = 46 Rstring str2 long len = 4 char ary[] = “This” Ruby Conf India 2012
  • 37. Shared Strings with slice str = "This is a very very very very very long string" str2 = str[1..-1] #str2 = str[22..-1] # 0 <= start_offset < 46-23 RString Heap str char *ptr long len = 46 VALUE shared T h i . . i n g RString str2 char *ptr long len = 45 Ruby Conf India 2012
  • 39. String.new(“learning”) Creating a string 23 characters or less is fastest Creating a substring running to the end of the target string is also fast When sharing same string data, memory and execution time is saved Creating any other long substring or string, 24 or more bytes, is slower. Ruby Conf India 2012
  • 40. RHash 1.8.7 :002 > {1 => "a", "f" => "b", 2 => "c"} => {1=>"a", 2=>"c", "f"=>"b"} 1.9.3p0 :001 > {1 => "a", "f" => "b", 2 => "c"} => {1=>"a", "f"=>"b", 2=>"c"} #1.8.7 #1.9.3 struct RHash { struct RHash { struct RBasic basic; struct RBasic basic; struct st_table *tbl; struct st_table *ntbl; int iter_lev; int iter_lev; VALUE ifnone; VALUE ifnone; }; }; struct st_table { struct st_table { struct st_hash_type *type; const struct st_hash_type *type; int num_bins; st_index_t num_bins; int num_entries; ... struct st_table_entry **bins; struct st_table_entry **bins; }; struct st_table_entry *head, *tail; }; struct st_table_entry { struct st_table_entry { st_data_t key; st_data_t key; st_data_t record; st_data_t record; st_table_entry *next; st_table_entry *next; }; st_table_entry *fore, *back; }; Ruby Conf India 2012
  • 41. RHash 1.8.7 st_table_entries key1 value key3 value x st_table key2 value x num_entries = 4 num_bins = 5 **bins key4 value x hash buckets - slots Ruby Conf India 2012
  • 42. RHash 1.9.3 st_table_entries 1x key1 value key2 value 3 4x 2 st_table 3 key3 value 4 2 3 num_entries = 4 num_bins = 5 **bins *head *tail 4 key4 value 1x 3 4x hash buckets - slots Ruby Conf India 2012
  • 44. C Extensions – why and when ? Performance Using C libraries from ruby applications Using ruby gems with native C extensions e.g. mysql, nokogiri, eventmachine, RedCloth, Rmagick, libxml-ruby, etc Since ruby interpreter is implemented in C, its API can be used Ruby Conf India 2012
  • 45. My fellow ist Patrick Shaughnessy Ruby Conf India 2012
  • 47. Thank you all for being patient and hearing me out ! Hope this helps you ! Ruby Conf India 2012

Editor's Notes

  1. Around 300 C files Around 100 .h header files
  2. Some Objects are fully specified by a VALUE, eliminating the need to create an actual object in Object Space. This saves a lot of processing cycles and does not functionally compromise the Object Model. These object types are: VALUE as an Immediate Object As we said above, immediate values are not pointers: Fixnum, Symbol, true, false, and nil are stored directly in VALUE. Fixnum values are stored as 31-bit numbers[Or 63-bit on wider CPU architectures.] that are formed by shifting the original number left 1 bit and then setting the least significant bit (bit 0) to ``1.&apos;&apos; When VALUE is used as a pointer to a specific Ruby structure, it is guaranteed always to have an LSB of zero; the other immediate values also have LSBs of zero. Thus, a simple bit test can tell you whether or not you have a Fixnum. There are several useful conversion macros for numbers as well as other standard datatypes shown in Table 17.1 on page 174. The other immediate values (true, false, and nil) are represented in C as the constants Qtrue, Qfalse, and Qnil, respectively. You can test VALUE variables against these constants directly, or use the conversion macros (which perform the proper casting).
  3. You save memory since there’s only one copy of the string data, not two, and: You save execution time since there’s no need to call malloc a second time to allocate more memory from the heap.
  4. When sharing same string data, memory is saved since there’s only one copy of the string data. When sharing same string data, execution time is saved since there’s no need to call malloc a 2 nd time to allocate more memory from the heap.