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

What's hot

5 collection framework
5 collection framework5 collection framework
5 collection frameworkMinal Maniar
 
Part II: LLVM Intermediate Representation
Part II: LLVM Intermediate RepresentationPart II: LLVM Intermediate Representation
Part II: LLVM Intermediate RepresentationWei-Ren Chen
 
Multiple inheritance possible in Java
Multiple inheritance possible in JavaMultiple inheritance possible in Java
Multiple inheritance possible in JavaKurapati Vishwak
 
openFrameworks 007 - graphics
openFrameworks 007 - graphicsopenFrameworks 007 - graphics
openFrameworks 007 - graphicsroxlu
 
Estrutura de dados em Java - Filas com lista encadeada
Estrutura de dados em Java - Filas com lista encadeada Estrutura de dados em Java - Filas com lista encadeada
Estrutura de dados em Java - Filas com lista encadeada Adriano Teixeira de Souza
 
Acesso a Banco de Dados em Java usando JDBC
Acesso a Banco de Dados em Java usando JDBCAcesso a Banco de Dados em Java usando JDBC
Acesso a Banco de Dados em Java usando JDBCLuiz Ricardo Silva
 
Конспект лекций по курсу "Шаблоны разработки ПО"
Конспект лекций по курсу "Шаблоны разработки ПО"Конспект лекций по курсу "Шаблоны разработки ПО"
Конспект лекций по курсу "Шаблоны разработки ПО"Sergey Nemchinsky
 
SwtBot: Unit Testing Made Easy
SwtBot: Unit Testing Made EasySwtBot: Unit Testing Made Easy
SwtBot: Unit Testing Made EasyAnkit Goel
 
ZIO: Powerful and Principled Functional Programming in Scala
ZIO: Powerful and Principled Functional Programming in ScalaZIO: Powerful and Principled Functional Programming in Scala
ZIO: Powerful and Principled Functional Programming in ScalaWiem Zine Elabidine
 
Object-oriented programming
Object-oriented programmingObject-oriented programming
Object-oriented programmingNeelesh Shukla
 
Programação Orientada a Objetos
Programação Orientada a ObjetosProgramação Orientada a Objetos
Programação Orientada a ObjetosIgor Takenami
 
SOLID Design Principles
SOLID Design PrinciplesSOLID Design Principles
SOLID Design PrinciplesAndreas Enbohm
 
Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection frameworkankitgarg_er
 
collection framework in java
collection framework in javacollection framework in java
collection framework in javaMANOJ KUMAR
 

What's hot (20)

5 collection framework
5 collection framework5 collection framework
5 collection framework
 
Part II: LLVM Intermediate Representation
Part II: LLVM Intermediate RepresentationPart II: LLVM Intermediate Representation
Part II: LLVM Intermediate Representation
 
Multiple inheritance possible in Java
Multiple inheritance possible in JavaMultiple inheritance possible in Java
Multiple inheritance possible in Java
 
openFrameworks 007 - graphics
openFrameworks 007 - graphicsopenFrameworks 007 - graphics
openFrameworks 007 - graphics
 
Estrutura de dados em Java - Filas com lista encadeada
Estrutura de dados em Java - Filas com lista encadeada Estrutura de dados em Java - Filas com lista encadeada
Estrutura de dados em Java - Filas com lista encadeada
 
Acesso a Banco de Dados em Java usando JDBC
Acesso a Banco de Dados em Java usando JDBCAcesso a Banco de Dados em Java usando JDBC
Acesso a Banco de Dados em Java usando JDBC
 
Awt and swing in java
Awt and swing in javaAwt and swing in java
Awt and swing in java
 
Конспект лекций по курсу "Шаблоны разработки ПО"
Конспект лекций по курсу "Шаблоны разработки ПО"Конспект лекций по курсу "Шаблоны разработки ПО"
Конспект лекций по курсу "Шаблоны разработки ПО"
 
SwtBot: Unit Testing Made Easy
SwtBot: Unit Testing Made EasySwtBot: Unit Testing Made Easy
SwtBot: Unit Testing Made Easy
 
ZIO: Powerful and Principled Functional Programming in Scala
ZIO: Powerful and Principled Functional Programming in ScalaZIO: Powerful and Principled Functional Programming in Scala
ZIO: Powerful and Principled Functional Programming in Scala
 
Object-oriented programming
Object-oriented programmingObject-oriented programming
Object-oriented programming
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Clean code
Clean codeClean code
Clean code
 
Programação Orientada a Objetos
Programação Orientada a ObjetosProgramação Orientada a Objetos
Programação Orientada a Objetos
 
SOLID Design Principles
SOLID Design PrinciplesSOLID Design Principles
SOLID Design Principles
 
Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection framework
 
inheritance c++
inheritance c++inheritance c++
inheritance c++
 
collection framework in java
collection framework in javacollection framework in java
collection framework in java
 
Collections framework in java
Collections framework in javaCollections framework in java
Collections framework in java
 
Java AWT
Java AWTJava AWT
Java AWT
 

Viewers also liked

Alcatel-Lucent 3HE00028CA
Alcatel-Lucent 3HE00028CAAlcatel-Lucent 3HE00028CA
Alcatel-Lucent 3HE00028CAsavomir
 
20 steps to build an awesome personal brand
20 steps to build an awesome personal brand20 steps to build an awesome personal brand
20 steps to build an awesome personal brandThe Virtual Specialist
 
แบบเสนอโครงร่างโครงงานคอมพิวเตอร์
แบบเสนอโครงร่างโครงงานคอมพิวเตอร์แบบเสนอโครงร่างโครงงานคอมพิวเตอร์
แบบเสนอโครงร่างโครงงานคอมพิวเตอร์kooker
 
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 (17)

Portafolio de evidencias
Portafolio de evidenciasPortafolio de evidencias
Portafolio de evidencias
 
Cbc p2 saldaña
Cbc p2 saldañaCbc p2 saldaña
Cbc p2 saldaña
 
Alcatel-Lucent 3HE00028CA
Alcatel-Lucent 3HE00028CAAlcatel-Lucent 3HE00028CA
Alcatel-Lucent 3HE00028CA
 
20 steps to build an awesome personal brand
20 steps to build an awesome personal brand20 steps to build an awesome personal brand
20 steps to build an awesome personal brand
 
แบบเสนอโครงร่างโครงงานคอมพิวเตอร์
แบบเสนอโครงร่างโครงงานคอมพิวเตอร์แบบเสนอโครงร่างโครงงานคอมพิวเตอร์
แบบเสนอโครงร่างโครงงานคอมพิวเตอร์
 
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

Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
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
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
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
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - 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
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 

Recently uploaded (20)

Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
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
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
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
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - 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
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 

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.