D for the Win
tomerfiliba.com
tomerfiliba.com
Alright, some basics; Everything that has to access persistent information frequently is bound by disk/network/whatever IO, and web programming is no different. The reason why languages such as Python and Ruby are very viable options for this task is they are quite a lot abstracted away from bare metal to hasten the development process. The wait for IO is quite long compared to logic execution, so even though we are executing more instructions to get the same job done, the resulting overhead isn't very significant.
CPU-Bound computations are most definitely will execute faster in statically compiled languages such as C/C++, D, golang relative to interpreted languages but in the context of web programming this is not the case. Even though; if rendering HTML is such a big pain in the ass that it is slowing you down a lot you can always use a library that is implemented in a language that's fast, say C, and use its wrappings in your scripting language of choice. I am not sure about to what extent this is supported in other languages but I know you can do this in Python, heck you can do this in golang, even though it is a relatively new language [1]. I wonder how the author will move to C10M world by optimizing the wrong thing.
- Automated tools like SWIG have weird limitations and are complex.
- Binding to a C library manually means you have to wrangle the data from a heapy, pointery dynamic language world into whatever format the C libary wants.
- Writing the C code to operate on the dynamic language's objects directly means you have to learn how the language works under the hood, and your C code will never be useful in any other language.
- Python and Ruby both have a GIL that prevents you from using multithreading to its full potential.
- The way dynamic languages lay out objects in memory causes an inherent slowness everywhere. Your app's slowness may well be a death of a thousand cuts, with no easily optimized hot spot.
I think anyone who has actually worked on a project built this way will appreciate the idea of a compiled language that is closer to the expressiveness of Python.
I remember this argument being made in favor of Java (over native compiled code) and there it at least had some credibility. Python and Ruby are far, far slower.
Certainly, the only credible/really important argument in favor of Python (or whatever alternative language you want to suggest) is programmer productivity. Get the feature out the door, and then when it's making money figure out how to optimize it. If I were going to pick on anything in the article, it's the long line of "}"s in the HTML generation example. One of the best arguments in favor of Python's indentation I've ever seen.
If you're writing frequently-run code in Python/Ruby/JS, or any such highly-dynamic-at-runtime language, then chances are very good that your CPU, memory access, CPU cache, etc are going to be part of your bottleneck.
Write in something that doesn't effectively turn an i7 into a Pentium 4 (and be sure to use efficient memory management techniques), and your chances of main bottlenecks being IO-only are much better.
The belief that IO is the only bottleneck is a self-defeating prophecy. It leads to code and techniques that cause CPU to become a bottleneck once again. Don't forget Wirth's Law.
If you care for your application performance you will quickly learn how to cache data (and that means figuring out algorithmic space and execution complexity). You will then, quickly care about how well your chosen programming language, libs and OS deal with memory allocations, instruction parallelization, on-die cache optimization, and so on.
And finally after all that, you will still care about I/O so you will figure out how to optmize your I/O access to benefit from hardware assumptions of a particular set of storage/network devices
Then you will look back at your solution and realize that your "use its wrappings in your scripting language of choice" is nothing more than a wrapper around another language. And then you will be wondering if it was worth starting with a different tool.
I've seen databases bottleneck on lots of different resources, even some virtual ones (unexpected serializing). But I'm very suspicious of people claiming that one must write webapps in low level languages "because speed". (And yes, I know there exist problems out there where this is true, the same way that there exist people out there that've won the lottery.)
Maybe a very small instance serving something fairly complex?
Does that mean that Erlang is the best? Of course not! It only means that Erlang was specifically designed for this sole use case, which only happens to encompass the whole "web" thingie.
It would be an overkill to use Erlang for single-threaded software that requires number crunching speed or for any kind of system scripting. Comparing Erlang to D or Python is stupid. As is (IMHO) using any of the latter for massively parallel servers.
This means they have the time for about ~200 million instructions per request (Ignoring internal disk I/O, or network I/O).
That amount of work is insane!
:.:.:
I want to say their doing something fundamentally wrong. And it has nothing to do with their language.
The slowness of their system can probably be blamed on slow database access, or some kind of initialization cost they're paying for every request (i.e.: calling into a binary like in the old CGI days, initializing the Python VM every time).
Un-Indexed databases, databases far away from front end servers (in terms of network topography), or weird VM things with python.
Something is bad, and if changing languages solved their problems, they are just sweeping an issue under the rug. It'll hit them in the face later, and harder. Be it developer knowledge, or architectural choices. It'll surface again, they'll (hopefully) be large, and the problem will sting harder too.
They're probably just aggregating 2 or 3 APIs, maybe hitting a database and then adding it all together.
That description can apply to almost any and all web applications and is inherently IO-bound.
People just sort of chant this, yet... if you upgrade from Python to something on the faster end of the spectrum, like D, you are very likely to still experience significant speed up, in my experience, even if you don't touch IO access patterns. You're even more likely to see a real latency decrease. And that's before we start actually multithreading or anything.
For all the work done on them in the past few years, the dynamic languages remain slow, slow, slow.
I think people often don't look at the math very carefully... if you do, say, half a dozen DB queries each less than 1ms, but your entire web page is clocking in at 50 or 100ms of rendering, all numbers that are very easy to see in real life (such as my own personal Django blog, where I've carefully counted each DB access and carefully indexed all of them), you are not actually spending all your time in IO wait.
One of the worst cases for a dynamic language is crawling a large object hierarchy, obtaining lots of tiny objects from them, and then merging them together in the end. You pay and pay and pay for the constant new object creation, reference count management, endless resolutions of methods, and all the other things dynamic languages are doing over and over and over (even when JITed).
Now, guess what "rendering a template" looks like internally.
Oh, and don't forget, if the DB returns in 1ms but your language reports the query took 5ms, you can't count the time it took your dynamic language to handle what came back from the DB as IO wait!
(I have to admit, I'm really done with the dynamic languages. It was fun when the megahertz went up every year, but now it's like wearing 20lb concrete shoes and trying to pretend that's not a problem, it doesn't affect my performance at all... and the 20lb is already after we cut it down from 40lb with all the JITs and stuff, which rhetoric notwithstanding simply do not produce anything like C-like performance in practice.)
It is not the case that I/O bottlenecks can always be overcome, but it can often be, depending on circumstances, provided one tries of course.
As someone working in VM research, I'm not entirely convinced this is true. Perhaps we should do some work to find out where most web applications really do spend their time.
Here's one real-world example: Rap Genius. They certainly aren't mathematicians or theoretical physicists, all they do is process text I think, but it appears they spend over half their time in the Ruby interpreter - not waiting on network or database (if I'm reading the graph correctly).
http://images.rapgenius.com/75aa2143d3e9bf6b769fc9066f6c40c8...
I remember seeing a post several years ago that XEN increases the likelihood of cache misses by 25-50%. Thus while the CPU looks to be at 100% processing power its really waiting on RAM/cache.
[0]http://www.techempower.com/benchmarks/#section=data-r9: in which python frameworks generally perform poorly compared to...anything else other than Ruby
If you have just a few thousand pages, with a few thousand bytes each in a normal (real) server, no your computer will keep everything at memory, and will only touch the disk for saving data. Also, if you have enough independent requests, throughput will not be network bound.
But CPython may still keep most of its time waiting for RAM. D is much better at this, as is Pypy.
For a concrete example, check out my Redis-based Twitter clone http://typesafe.com/activator/template/redis-twitter-clone, running at https://clockwork-semaphore.herokuapp.com/#.
..or Dwarf Fortress player ;)
If their system was truly just IO bound, then moving to D wouldn't help them.
For example, the amount of housekeeping python does in order to execute a function call is staggering. It leads to all sorts of nice functionality, but nevertheless (plus C++/D does it almost entirely without housekeeping. Either no housekeeping, or 1 level of indirection).
Python has so many indirections for a function call it hardly even makes sense to talk about it in numbers of indirects.
Assembly hello world on my machine : 86,607 cpu cycles (of which < 20 actually in the program) Syscalls used by the assembly version : 2 (write and exit)
Python hello world on my machine (.pyc was available) : 59,099,731 instructions (including half a million branch misses) Syscalls used by python to execute 'print "hello, world"' : 1139 (each of which causes a program reschedule)
These programs do the same thing. Programmers often forget that things they take for granted are not in fact free, they may not even be O(1). Memory allocation. Subprocess execution. Function calls in scripting languages. Syscalls. Writing to files. Allocation of bytes on disks. All of these things come at a really, really high cost, and most not even O(1) costs (e.g. memory allocation is O(N^2) on a busy server as long as things actually fit in main memory, and O(N^4) or even worse when using virtual memory).
Sadly using memory does not even have bounded complexity. At some point, just attempting to use virtual memory might cause virtual memory to be allocated just for the lookup. This is generally referred to as "thrashing" and you're very likely to have rebooted your machine before this completes because it'll be frozen for minutes, sometimes hours, if this happens.
Likewise the memory model is useful, but huge. Strings in C++ take one byte + the actual contents of the string. Strings in python take up 60 bytes + twice the length of the string. And that's assuming you just set a variable to the string. If you construct the string, the difference is going to be much bigger.
The point here is that things that are io-bound (esp. memory bound) in python may be cpu-bound in C++ or D, simply because you avoid doing all the indirections that higher level languages do.
I think you mean the reverse: "things that are cpu-bound (esp. memory bound) in python may be io-bound in C++ or D".
Once loaded into memory, any program which is bound by IO to memory (i.e. moving the stack from memory to caches/registers) will show up in tools not as being IO bound, but CPU bound.
And yes, CPU bound programs will benefit greatly from moving the hotspots into a linked module written in C or Cython.
I have no problem with moving away from Python (I'm in the process of doing this myself), but the costs associated with re-writing an entire program (especially one complicated enough to only handle 50 requests per second) are non trivial, and if there was simply a small CPU hotspot, it could have been smoothed away in a number of ways that don't involve learning a new language.
In short, everything points towards OP moving to D because of a personal desire instead of a real business case.
But these days, languages have features that may be completely orthogonal to other languages. Automatic translation may not be possible. Still it would be by far the cheapest solution.
>1139 (each of which causes a program reschedule)
I thought system calls were packaged into the binary itself and didn't necessarily cause a job to re-schedule. But just caused a context switch to take place, then execution continues.
I thought re-scheduling only happened on interrupt, or a thread reaching a blocked stated.
Could you clarify this for me, I'm interested.
D people who have some knowledge of Nimrod (or Nimrod people who have good knowledge of D) - where do you think D outdoes Nimrod? D is more mature, with a larger community, and a recognized brand - granted, and these are NOT trivial things -- in practice, they usually matter more than any specific feature. Yet, my question in this case IS about language/environment features.
As far as I can tell, all the examples in the article can be done at least as easily/tersely/nicely, if not more so, in Nimrod.
http://blog.thecybershadow.net/2014/03/21/functional-image-p...
I'd be interested to know if the same expressiveness is possible in other languages without sacrificing speed.
I am curious what led the author to be dismissive of Go in such a strongly negative manner. Lack of generics? Disagree with certain language design choices? Too many cuddly caricatures of gophers?
- low-level hardware control (c,D,...) implicitely concurrent
- explicitely concurrent higher level components (go, erlang maybe)Therefore I'd bundle it with C and D rather than Erlang.
I've been writing Go full-time for over 2 years and used to write mostly Java/C#, so I should know. When I started with Go and ported many of my personal Java applications, they all were much more maintainable and straight forward in Go.
Of course C had always been favorite language, and all I ever really wanted was a "modern" C, so I am probably biased.
Now, whether go turns out to be good at that task is another story
For example: the difference in initialisation of simple data types vs slices and maps. For an application programmer these are weird inconsistencies. But they make sense in the domain.
Or the way error handling works. Very tedious to have to do-check, do-check, and not be able to have automatic upwards delegation. But in system programming it's about robustness, not ease of development. A database server can't just restart if it has a file or memory problem. There needs to be a solution and it needs to be immediately next to the problem.
That being said, I've followed a similar pattern in writing Go web apps. I passed errors upwards from their originating site to the HTTP handler functions, because that was where the error handling was possible with the best context.
That's a great feature. I don't see many languages investing enough focus into this kind of "delegation wiring."
struct A { int a; alias a this; } struct B { A a; alias a this; } struct C { B b; alias b this; }
static assert(C(42) == 42);
Combined with D's support for compile-time protocols, this allows for some very expressive, powerful and lighting fast code.
http://golang.org/doc/effective_go.html#embedding
http://golang.org/ref/spec#Struct_types
Note that there's also interface embedding which is a different thing.
Yes, it's a different feature, but is not multiple inheritance either (although I understand why, at a first glance, you'd think it would seems like that). It's just composition. In this new example, look how you can do b.myInt, even though b is now a bar, not a foo. In fact this happened in the old example too, but it was invisible. This is how the Lock function accessed the mutex.
Here's what Walter said at the time when asked why it took so long:
I've been intending to for a while, it took a while for me
to clean it up, check all the licenses, and get it into a
presentable form.
Essentially, it's pretty obvious that the world has changed,
and closed source is no longer acceptable for a mainstream
product that people will be relying on. Open source is the
future, and it's past time for dmd to join the party!Over in the D community we're very proud of our use of the Boost license.
Go's syntax is really easy to most programmers who is willing to learn. It's probably just 1 days work to pick it up. It's very similar to Swift's syntax in many aspects, and I don't hear anyone complaining Swift's syntax is not intuitive and just for the sake of being different.
Perhaps instead of just claiming you can give us some examples on "syntax is all over the place" part?
This is exactly how this sentence should look like, no need for any language at the beginning. While syntax does matter (and I only recently arrived at this conclusion) its "intuitiveness" or "similarity" is utterly unimportant. You either are a "real programmer" and have no problem picking up different syntaxes and semantics, or you're not. That's all there is to it.
Also, swift has an API that's familiar to ObjC devs which means it's just changing brackets. It's pretty easy to port a ObjC program to swift line by line.
Every time I get some GNU/Linux GUI utility running very very slow and check the code, it is Python under the hood.
I even backported the C metadata parser to CentOS 3 and 4, because it was a whole different experience altogether:
http://lists.centos.org/pipermail/centos-devel/2007-May/0017...
Now I could start bashing Java and the others, but I hope I don't need to and that you already realized that your comment is a bit unfair.
If the code compiles, it must run without error?