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

OCL: Object Constraint Language
OCL: Object Constraint LanguageOCL: Object Constraint Language
OCL: Object Constraint Language
elliando dias
 
닷넷프레임워크에서 Redis 사용하기
닷넷프레임워크에서 Redis 사용하기닷넷프레임워크에서 Redis 사용하기
닷넷프레임워크에서 Redis 사용하기
흥배 최
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
kamal kotecha
 
Encapsulamento com Descritores em Python
Encapsulamento com Descritores em PythonEncapsulamento com Descritores em Python
Encapsulamento com Descritores em Python
Luciano Ramalho
 

What's hot (20)

Javascript Prototype Visualized
Javascript Prototype VisualizedJavascript Prototype Visualized
Javascript Prototype Visualized
 
Url Connection
Url ConnectionUrl Connection
Url Connection
 
SOLID & IoC Principles
SOLID & IoC PrinciplesSOLID & IoC Principles
SOLID & IoC Principles
 
Aula 5 encapsulamento, associação, polimorfismo, interfaces
Aula 5   encapsulamento, associação, polimorfismo, interfacesAula 5   encapsulamento, associação, polimorfismo, interfaces
Aula 5 encapsulamento, associação, polimorfismo, interfaces
 
Unit 2 Java
Unit 2 JavaUnit 2 Java
Unit 2 Java
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
OCL: Object Constraint Language
OCL: Object Constraint LanguageOCL: Object Constraint Language
OCL: Object Constraint Language
 
Java data types
Java data typesJava data types
Java data types
 
Redis data modeling examples
Redis data modeling examplesRedis data modeling examples
Redis data modeling examples
 
Unit 4 Java
Unit 4 JavaUnit 4 Java
Unit 4 Java
 
닷넷프레임워크에서 Redis 사용하기
닷넷프레임워크에서 Redis 사용하기닷넷프레임워크에서 Redis 사용하기
닷넷프레임워크에서 Redis 사용하기
 
Java swing
Java swingJava swing
Java swing
 
Derivativos no Brasil
Derivativos no BrasilDerivativos no Brasil
Derivativos no Brasil
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
Aula 04 - POO - Estruturas de Controle e Repetição
Aula 04 - POO - Estruturas de Controle e Repetição Aula 04 - POO - Estruturas de Controle e Repetição
Aula 04 - POO - Estruturas de Controle e Repetição
 
2019-2 - Algoritmos - Aula 06 A - Tomada de Decisão
2019-2 - Algoritmos - Aula 06 A - Tomada de Decisão2019-2 - Algoritmos - Aula 06 A - Tomada de Decisão
2019-2 - Algoritmos - Aula 06 A - Tomada de Decisão
 
OOP C++
OOP C++OOP C++
OOP C++
 
Encapsulamento com Descritores em Python
Encapsulamento com Descritores em PythonEncapsulamento com Descritores em Python
Encapsulamento com Descritores em Python
 
Java Generics: a deep dive
Java Generics: a deep diveJava Generics: a deep dive
Java Generics: a deep dive
 
Grails GORM - You Know SQL. You Know Queries. Here's GORM.
Grails GORM - You Know SQL. You Know Queries. Here's GORM.Grails GORM - You Know SQL. You Know Queries. Here's GORM.
Grails GORM - You Know SQL. You Know Queries. Here's GORM.
 

Viewers also liked

แบบเสนอโครงร่างโครงงานคอมพิวเตอร์
แบบเสนอโครงร่างโครงงานคอมพิวเตอร์แบบเสนอโครงร่างโครงงานคอมพิวเตอร์
แบบเสนอโครงร่างโครงงานคอมพิวเตอร์
kooker
 
Summative Presentation
Summative PresentationSummative Presentation
Summative Presentation
montie1989
 
Monografía david velas
Monografía david velasMonografía david velas
Monografía david velas
david velasco
 
Referencias Bibliograficas con normas APA
Referencias Bibliograficas con normas APAReferencias Bibliograficas con normas APA
Referencias Bibliograficas con normas APA
Lola Costa
 
збери сам ферма
збери сам фермазбери сам ферма
збери сам ферма
Anna Polud
 

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?

MacRuby & HotCocoa
MacRuby & HotCocoaMacRuby & HotCocoa
MacRuby & HotCocoa
Thilo 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.0
Kartik Sahoo
 
Introduction to Ruby on Rails
Introduction to Ruby on RailsIntroduction to Ruby on Rails
Introduction to Ruby on Rails
Manoj Kumar
 
Auto cad 2006_api_overview
Auto cad 2006_api_overviewAuto cad 2006_api_overview
Auto cad 2006_api_overview
scdhruv5
 

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

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 

Recently uploaded (20)

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 

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.