Python vs ruby performance

Raising errors

In Python

class Triangle():
    NUMBER_OF_SIDES = 3

    def __init__(self, *sides):
        self.__validate_number_of_sides(sides)

        self.sides = sides

    def __validate_number_of_sides(self, sides):
        if len(sides) != self.NUMBER_OF_SIDES:
            raise ValueError(f"expected {self.NUMBER_OF_SIDES} sides")


Triangle(1)
# => ValueError: expected 3 sides

In Ruby

class Triangle
  NUMBER_OF_SIDES = 3

  def initialize(*sides)
    validate_number_of_sides(sides)

    @sides = sides
  end

  private

  def validate_number_of_sides(sides)
    raise ArgumentError, "invalid number of sides (expected #{NUMBER_OF_SIDES})" if sides.size != NUMBER_OF_SIDES
  end
end

Triangle.new(1)
# invalid number of sides (expected 3) (ArgumentError)

In JavaScript

class Triangle {
  constructor(...sides) {
    this._validateNumberofSides(sides);

    this.sides = sides;
  }

  _validateNumberofSides(sides) {
    const maxNumberOfSides = 3;

    if (sides.length != maxNumberOfSides) {
      throw new Error(`invalid number of sides (expected ${maxNumberOfSides})`);
    }
  }
}

new Triangle(1);
// => Error: invalid number of sides (expected 3)

Python

Almost everyone knows Python is a general-purpose, high-level programming language. But only a few know that it was organically developed as a prototyping language in a scientific community. It was created by Guido Van Rossum. Python has elegant syntax and readable code. If you have no idea about programming, then it can be the first language for your programming career. Python suits you best in data science, data analytics, machine learning, and lots more. If the prototype worked, then it could easily be translated into C++. Python motivated a massive number of people around the world to start learning Python. As we know, Python is one of the simplest programming languages, but it has only one best way to do something.

Advantages of Python

Here are the pros/benefits of using Python:

  • Python is a powerful object-oriented programming language.
  • Uses an elegant syntax, making the program you write easier to read.
  • Python comes with a large standard library, so it supports many common programming tasks.
  • Runs on various types of computers and operating systems: Windows, macOS, Unix, OS/2,etc.
  • Very simple syntax compared to Java, C, and C++ languages.
  • Extensive library and handy tools for developers
  • Python has its auto-installed shell
  • Compared with the code of other languages, python code is easy to write and debug. Therefore, its source code is relatively easy to maintain.
  • Python is a portable language so that it can run on a wide variety of operating systems and platforms.
  • Python comes with many prebuilt libraries, which makes your development task easy.
  • Python helps you to make complex programming simpler. As it internally deals with memory addresses, garbage collection.
  • Python provides an interactive shell that helps you to test the things before its actual implementation.
  • Python offers database interfaces to all major commercial DBMS systems.

Web Apps: Ruby Has The Edge

Web development remains one of the chief arenas in which Ruby and Python compete. Sure, there is server scripting, enterprise apps, mobile apps, and now machine learning, but the traditional user of these languages was the web developer. In the web applications arena, for better or for worse, Ruby has been the much more dominant player, thanks to Ruby On Rails. Ruby’s flexibility, fully promoted by its philosophy that allows multiple ways of getting the same thing accomplished, is a boon to web developers. It’s tempting to think that one simple way of doing things will work for everyone, but when the use cases that web developers diverge as widely as they do, it’s only practical to let multiple approaches flourish. In this case, the success of Ruby is reminiscent of that of C++, a much-maligned language that has succeeded so widely because it lets any team pick whichever particular subset of the language they want to use.

Ruby On Rails is like Ruby on steroids, complete with extensive behind the scenes code generation and server-side metaprogramming that would make coders in a more staid language community raise eyebrows. Indeed this was the case when Django, over in Python land, emulated the Rails MVC approach and immediately faced pushback from Pythonistas who thought the framework was doing too much and getting too complex, out of line with the Pythonic emphasis on readability. Where Python programmers, and Django, went with simplicity, Ruby On Rails went with power and flexibility. True, it can get complex, but the flexibility has proven valuable for web developers. This has led to Rails being almost a rite of passage for “cutting edge” startups especially those developing B2C platforms, with a plethora of big successes such as Airbnb, Twitter, Github, and others too many to count. Rails development is insanely fast, hyper productive, and allows an early stage startup to iterate flexibly with next to no technical staff beyond a couple of core ROR developers. Ruby has also done well in devops, with tools like Chef taking full advantage of the expressive power of the scripting language.

All this does not mean that Python is a slouch in web development. It has some unique tricks all its own: speed and a super large ecosystem. There is a perception that Python is faster than Ruby, and this has often led teams to prefer it over Ruby for web development. The Ruby community is painfully aware of this, and Ruby has gotten way faster over the years. Now, in benchmarks, Ruby performs just about as well as Python, if not better. Still, that’s not enough for the Ruby community, whose Ruby Version 3 was specifically planned to be much faster than Ruby 2, and, pointedly, aims to be much faster than Python3. Either way, the battle is on.

The Language:

The Ruby on Rails web framework is built using the Ruby programming language while the Django web framework is built using the Python programming language.

This is where many of the differences lay. The two languages are visually similar but are worlds apart in their approaches to solving problems.

Ruby is designed to be infinitely flexible and empowering for programmers. It allows Ruby on Rails to do lots of little tricks to make an elegant web framework. This can feel even magical at times, but the flexibility can also cause some problems. For example, the same magic that makes Ruby work when you don’t expect it to can also make it very hard to track down bugs, resulting in hours of combing through code.

Python takes a more direct approach to programming. Its primary goal is to make everything visible to the programmer. This sacrifices some of the elegance that Ruby has but gives Python a big advantage when it comes to learning to code and debugging problems efficiently.

A great example that shows the difference is working with time in your application. Imagine you want to get the time one month from this very second. Here is how you would do that in both languages:

Ruby
require 'active_support/all'
new_time = 1.month.from_now

Python
from datetime import datetime
from dateutil.relativedelta import relativedelta
new_time = datetime.now() + relativedelta(months=1)

Notice how Python requires you to import specific functionality from datetime and dateutil libraries. It’s explicit, but that’s great because you can easily tell where everything is coming from.

With the Ruby version, a lot more is hidden behind a curtain. We import some active_support library and now all of a sudden all integers in Ruby have these “.days” and “.from_now” methods. It reads well, but it’s not clear where this functionality came from within active_support. Plus, the idea of patching all integers in the language with new functionality is cool, but it can also cause problems.

Neither approach is right or wrong; they emphasize different things. Ruby showcases the flexibility of the language while Python showcases directness and readability.

Conclusion

Despite the noisy arguments from both languages’ camps, it is impossible to say whether one language is overall ‘better’ than the other. It’s clear that each has some areas it is better suited to, because of its features and support from other users in the same area. For Ruby this is web development via the Rails framework, and for Python it is scientific and academic programming. And each has some features or capabilities that the other does not have or does not do well.

The two languages also espouse radically different philosophies. Ruby focusses on giving developers the freedom to do whatever they want and staying out of their way. Python insists on ease of learning and use by zeroing on only on the one right way to do something. This produces an interesting culture split between the camps – Python developers are somewhat conservative and value stability over change, developments and new features are added slowly. Ruby adherents seem to thrive on change and freedom. For instance the Rails framework is constantly changing, and in fact many of the changes and new features in Python are first tested in Ruby. Read more about these different mindsets here.

Features of Python

Here are the important features of Python:

  • Easy to learn, read, and maintain
  • It can run on various hardware platforms & using the same interface.
  • You can include low-level modules to the Python interpreter.
  • Python offers an ideal structure and support for large programs.
  • Python offers support for automatic garbage collection.
  • It supports an interactive mode of testing and debugging.
  • It offers high-level dynamic data types and also supports dynamic type checking.
  • Python language can be integrated with Java, C, and C++ programming code
  • High-performance
  • Simple, minimal syntax
  • Fast compilation times
  • Statically linked binaries which are simple to deploy

Passing named/keyword arguments, with options

In Python

def my_function(a, b, c=3, **kwargs):
    return f"a:{a}, b:{b}, c:{c}, kwargs:{kwargs}"


print(my_function(b=2, a=1, d=4, e=5, f=6))
# => a:1, b:2, c:3, kwargs:{'d': 4, 'e': 5, 'f': 6}

In Ruby

def my_function(a:, b:, c: 3, **kwargs)
  "a:#{a}, b:#{b}, c:#{c}, kwargs:#{kwargs}"
end

puts(my_function(b: 2, a: 1, d: 4, e: 5, f: 6))
# => a:1, b:2, c:3, kwargs:{:d=>4, :e=>5, :f=>6}

In JavaScript

function myFunction({ a, b, c = 3, options = {} } = {}) {
  return `a:${a}, b:${b}, c:${c}, options:${JSON.stringify(options)}`;
}

console.log(myFunction({ b: 2, a: 1, options: { d: 4, e: 5, f: 6 } }));
//=> a:1, b:2, c:3, options:{"d":4,"e":5,"f":6}

Ruby Vs Python: Code Side-By-Side

Ruby code and Python code has a lot in common, but there are subtler differences, especially in coding idioms driven largely by philosophical differences. Both are dynamic, interpreted languages. Both use white space and don’t have the braces made popular by C, C++, and Java, among other languages. These languages are truly versatile, however, as revealed by the paradigms they support: procedural, imperative, functional, and object-oriented. Yes, certain super functional-style code is far easier to write in Ruby than in Python, but Python, despite its drive for simplicity, can be used in ways rather similar to Ruby. Ruby, however, tends to be more expressive, and strikes a bit closer to functional languages like Lisp or Scheme than Python. Syntactically, and in many other ways, Ruby code looks a lot more like Python.

Here is a simple example that illustrates how close these two really are, while being far from the clones they might look like on the surface:

Fibonacci function in Ruby

def fib(n)

    n < 2 ? n : fib(n-1) + fib(n-2)

end

alias :fibonacci :fib

Fibonacci function in Python

def fib(n):

    if n < 2:

        return n

    else:

        return fib(n-1) + fib(n-2)

The Python code is just a tad simpler, while the Ruby code prefers power over simplicity. Still, both of these are much closer than would be examples in Java, C++, and other languages. What this means is that if your team ever has to switch language, moving from Ruby to Python or vice versa, while often considered inconceivable by deep enthusiasts in either software development camp, the sky would not exactly fall down. The learning curve is much easier to scale for developers and teams moving from one to the other, than it would be to move to a language such as C, C#, or even Erlang.

Ruby vs Python performance: similarities and differences

Conclusion

When deciding on which programming language to use for web development, remember that Ruby and Python have different goals.

  • Python initially was created for complex mathematical calculations, great accuracy, processing of very large amounts of data.
  • Python is a scripting language. It allows you to write a framework or connect to any libraries, even in other languages. Python has more libraries and a larger community than Ruby.
  • Ruby is perfect for prototyping and MVPs, which is why it’s so popular with startups.
  • Ruby is faster, but Python is more versatile.

Choose Ruby if you:

  • need to get the solution in the shortest time
  • know that innovation matters and want your product to be deployed using the best modern approaches
  • trust in readable code
  • believe in the magic of programming tools

Choose Python if you:

  • need Python-specific libraries
  • appreciate out-of-box functionality and good documentation
  • have a project that requires stability over innovative features
  • work with artificial intelligence, machine learning or big data

So, how do you choose a programming language for your project?

Frankly, the decision is up to you. Here, at Sloboda Studio we are open to helping you with this choice.

Когда выбрать Python?

Python будет лучшим выбором для сложных научных решений и приложений в облаке. Он также используется для разработки масштабируемых приложений, которые обладают преимуществом гибкости и могут управлять переменными рабочими нагрузками.

Создавая приложения с помощью Python, можно выйти за рамки разработки веб-приложений, чем при использовании Ruby. Это можно объяснить тем, что Python используется в разных отраслях, от науки о данных до робототехники. Вот почему сообщество Python — одно из самых лучших. Благодаря постоянно растущей экосистеме Python вы получите полный контроль над процессом разработки и не останетесь без ответа. В Stack Overflow, крупнейшем и пользующемся наибольшим доверием онлайн-сообществе разработчиков, задавали около полутора миллионов вопросов о Python.

Также Python в сочетании с библиотекой TensorFlow значительно упрощает разработку решений на основе ИИ, поскольку имеет встроенные алгоритмы машинного обучения. Язык также широко используется для обработки и анализа данных. Он особенно полезен при анализе аудио и видео, поскольку язык позволяет визуализировать данные и обрабатывать их.

Что касается написания различных ботов для социальных сетей или парсинга данных, то думаю в этом случае лучше выбрать язык Python. Во-первый у языка для есть богатый набор библиотек, которые обновляются и имеют обширное сообщество. Во-вторых по мере развития вашего проекта, вам придется внедрять дополнительные функции, например для работы с машинным обучением, парсинг данных или анализ больших данных, и для этих случаев опять же у python есть богатый набор библиотек. Ну и в-третьих у языка python огромное сообщество по всему миру, и поэтому в случае если у вас возникнут какие-либо вопросы или вы столкнетесь с проблемой, то всегда сможете получить помощь и спросить об этом на различных форумах.

Сравнение Python и Ruby

Первое, что следует отметить, это
популярность Ruby в сфере создания сайтов.
На этом языке, например, созданы Basecamp,
Github, Slideshare.

И Python, и Ruby являются объектно-ориентированными
языками, динамичными и гибкими. Но к
решению проблем они подходят по-разному.
Ruby предлагает несколько вариантов для
выбора, а Python — только один. Но этот факт
можно считать как преимуществом, так и
недостатком каждого из языков.

Самый распространенный фреймворк Ruby это Ruby-on-Rails. Он довольно похож на Django — фреймворк Python. Обе эти технологии имеют многочисленные сообщества.

Можно сказать, что в том, что касается
веб-разработки, оба фреймворка предлагают
примерно одинаковые условия, поскольку
каждую отдельную проблему можно решить
и при помощи Ruby-on-Rails, и с использованием
Django. Обе технологии быстры и эффективны.

Why use Python: pros and cons

No one’s perfect, right? Python has its good and bad aspects too. Let’s review Python’s pros and cons.

Pro #1: Easy and fast to work with

Python readability is great, and the code is strictly structured. Moreover, the language is rich in features, gems, and libraries, so it’s easy to find a solution for almost any problem. Python is especially good for exploratory analysis and various paradigms of programming since it orients to objects and adopts functional programming features. All in all, the data structure in Python is pretty convenient to work with.

Pro #2: Community

Python has a global community with millions of developers. This is bigger than the Ruby community since the technology itself is older. This community also has a larger scientific approach.

Pro #3: A LOT of libraries

Machine learning, artificial intelligence, big data and data science – Python has a library for almost everything you might need.

Infographics on Ruby and Python usage

To address both the pros and cons of Python, we should talk about the negative features, too.

Con #1: Speed limitations and parallel tasks

Since Python is an interpreted language, it can take some time for a performance. For instance, this is one of the reasons Python is not a very good choice for mobile development. 

In addition, Python works inefficiently with parallel threads and tasks and has difficulties when switching to higher versions (e.g, from Python 2 to Python 3). Though, this programming language is still great for web development, Linux and artificial intelligence.

Con #2: Considerable memory consumption

Due to large and flexible data-types, Python often takes up a considerable amount of memory. If your project requires a lot of memory, Python is not your friend.

Con #3: Runtime Errors

Python programmers often experience runtime errors. The language is dynamically-typed, therefore the errors only appear during runtime. This is not terrible, but it still means that working with Python requires more testing and attention.

Conclusion

After having a close look at the comparison between Python vs Ruby, we have concluded that both of these programming languages are efficient and highly reliable. Apart from that, these languages also have community support. You should choose Python when you need to deal with computation, such as statistical computation and data computing. It is the best programming language to process and performs statistical and mathematical operations over large data sets. 

On the other hand, Ruby fits in the scenarios where you need to deal with the heavy amount of data in your web application or website. If you want to develop web applications, both of these programming languages offer the best framework for web development. But as I have mentioned earlier, Ruby is the best choice when it comes to flexibility in web development. Whenever you get into trouble while developing in Ruby, you can get the instant support of other developers using Ruby’s community.

Advertisements

What is Python Used For

The first implementation of Python was born in 1989 in the Netherlands by Guido van Rossum.

If you have a suspicion about the name: yes, it was named for the famous British TV show Monty Python. This programming language is open source. Python has an impressive community and developing not the least because of it. People were appreciated for the job that van Rossum did and he was elected as a dictator of Python forever.

    Python is not that object-oriented as Ruby, but still can be. The motto is “A simple thing is better than a complex thing. A complex thing is better than a complicated thing”. It uses the whitespace in order to control the flow in your program. This could be actually useful and significant: if things can be indented in different ways, their meaning in a program will be also different. You can understand the logic of a program that was written in Python and what is going on with a single look if you understand the structure.

Advantages and disadvantages of Python

Let’s figure out why you should use Python and why it is cool:

  • It is extensible. Python can be extended to a variety of languages. For example, you can write a block of your code in C or C++, which is pretty handy when it is needed for your project.

  • It is productive. The fact that Python is simple and comes with extensive libraries makes Python programmer is at least a bit more productive than those who work with C++ or Java.

  • Internet of Things and related opportunities.  Python runs such platforms like RaspberryPi and it definitely has the bright future for the Internet of Things.

  • Simplicity. While working with languages like Java, you have to create a whole class just to print “Hello World”. You can do this only with a print statement in Python.

Well, looks like Python is a great choice, but what about its notable drawbacks?

  • Design Restrictions. We know that Python is dynamically typed programming language. In other words, you don’t have to declare the type of each variable when you write the code. Python uses duck-typing, which means that if something looks like a duck, acts like a duck, it must be a duck, eventually. But it can lead to runtime errors, though.

  • Speed limitations. As we know, Python code can be executed line by line. But since it is interpreted it can lead to slow execution, which is not necessarily a big problem, though, except the case where speed is important for your project.

  • Redundant simplicity. It’s not a joke. Such simplicity can become a problem. For example, if you switch to Java after years with Python, you’ll see that Java’s verbosity is unnecessary.

  • Browser and mobile computing drawbacks. Despite the fact that Python is a brilliant server-side programming language, you can barely see it on the client-side of the project as well as on the smartphone-based apps. For example, you can check out the application called Carbonelle, which is built with Python.

  • Weak database access layers. Python’s database access layers are weaker than Open Database Connectivity and Java Database Connectivity due to poor development. As a consequence, you’ll rarely see Python’s database access layers in biggest enterprises.

Итоги

Проанализировав все выданные предупреждения диагностик общего назначения и убрав все ложные срабатывания, я пришёл к следующему распределению ошибок:

Большая часть срабатываний в Ruby пришлась на предупреждение V610 (369 срабатываний!), но даже если их исключить, то ситуация не изменится: по количеству подозрительных мест Python опережает своего конкурента.

Наиболее частой оказалась диагностика V595: в коде Python она встретилась 17 раз, в коде Ruby – 37.

Но интереснее всего соотношение плотности ошибок. По этой характеристике Python также однозначно побеждает. С результатами расчётов можно ознакомиться в таблице:

Может показаться, что ошибок многовато. Это не так. Во-первых, не все из найденных ошибок критичны. Например, упомянутая ранее диагностика V610, выявляет ошибки с точки зрения языка С++. Однако на практике для используемого набора компиляторов результат может быть всегда правильным. Хотя от этого ошибки не перестают быть ошибками, они никак в данный момент не сказываются на работе программы. Во-вторых, нужно учитывать размер проверенного кода. Поэтому можно говорить о высоком качестве этих проектов. Пока эта оценка субъективна, так как ранее мы не вычисляли плотность ошибок у проверенных проектов. Но постараемся это делать в дальнейшем, чтобы впоследствии можно было делать сравнения.

Заключение

Языки Python и Ruby очень популярны: на них пишут миллионы разработчиков со всего мира. При такой активности проектов и комьюнити, хорошем качестве кода, отличном тестировании и использовании статического анализа (оба проекта проверяются с помощью Coverity) сложно найти большое количество ошибок. Тем не менее, PVS-Studio удалось найти несколько подозрительных мест. Но стоит понимать, что именно регулярная проверка кода может серьёзно облегчить жизнь разработчикам. Лучше всего править ошибку сразу до того, как изменения попадут в репозиторий и в релиз — статический анализатор в этом может помочь, как никто другой.

Предлагаю всем желающим попробовать PVS-Studio на своих проектах.

Рейтинг
( Пока оценок нет )
Понравилась статья? Поделиться с друзьями:
Ваша ОС
Добавить комментарий

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: