Scan HTML faster with SIMD instructions: Chrome edition

Modern processors have instructions to process several bytes at once. Effectively all processors have the capability of processing 16 bytes one once. These instructions are called SIMD, for single instruction, multiple data.

It was once an open question whether these instructions could be useful to accelerate common tasks such as parsing HTML or JSON. However, the work on JSON parsing, as in the simdjson parser, has shown rather decisively that SIMD instructions could, indeed, be helpful in breaking speed records.

Inspired by such work, the engine under the Google Chrome browser (Chromium) has adopted SIMD parsing of the HTML inputs. It is the result of the excellent work by a Google engineer, Anton Bikineev.

The approach is used to quickly jump to four specific characters: <, &, \r and \0. You can implement something that looks a lot like it using regular C++ code as follows:

void NaiveAdvanceString(const char *&start, const char *end) {
  for (;start < end; start++) {
    if(*start == '<' || *start == '&' 
        || *start == '\r' || *start == '\0') {

A ‘naive’ approach using the SIMD instructions available on ARM processors looks as follows. Basically, you just do more or less the same thing as the naive regular/scalar approach, except that instead of taking one character at a time, you take 16 characters at a time.

void AdvanceString(const char *&start, const char *end) {
  uint8x16_t quote_mask = vmovq_n_u8('<');
  uint8x16_t escape_mask = vmovq_n_u8('&');
  uint8x16_t newline_mask = vmovq_n_u8('\r');
  uint8x16_t zero_mask = vmovq_n_u8('\0');
  uint8x16_t bit_mask = {16, 15, 14, 13, 12, 11, 10, 9, 8,
                            7, 6, 5, 4, 3, 2, 1};
  static constexpr auto stride = 16;
  for (; start + (stride - 1) < end; start += stride) {
    uint8x16_t data = vld1q_u8(reinterpret_cast<const uint8_t *>(start));
    uint8x16_t quotes = vceqq_u8(data, quote_mask);
    uint8x16_t escapes = vceqq_u8(data, escape_mask);
    uint8x16_t newlines = vceqq_u8(data, newline_mask);
    uint8x16_t zeros = vceqq_u8(data, zero_mask);
    uint8x16_t mask = vorrq_u8(vorrq_u8(quotes,zeros), 
           vorrq_u8(escapes, newlines));
    uint8x16_t matches = vandq_u8(bit_mask, mask);
    int m = vmaxvq_u8(matches);
    if(m != 0) {
      start += 16 - m;
  for (;start < end; start++) {
    if(*start == '<' || *start == '&' 
       || *start == '\r' || *start == '\0') {

If you have a PC with an Intel or AMD processor, you can do the equivalent using SSE2 instructions:

void AdvanceString(const char*& start, const char* end) {
    const __m128i quote_mask = _mm_set1_epi8('<');
    const __m128i escape_mask = _mm_set1_epi8('&');
    const __m128i newline_mask = _mm_set1_epi8('\r');
    const __m128i zero_mask = _mm_set1_epi8('\0');

    static constexpr auto stride = 16;
    for (; start + (stride - 1) < end; start += stride) {
        __m128i data = _mm_loadu_si128(
           reinterpret_cast<const __m128i*>(start));
        __m128i quotes = _mm_cmpeq_epi8(data, quote_mask);
        __m128i escapes = _mm_cmpeq_epi8(data, escape_mask);
        __m128i newlines = _mm_cmpeq_epi8(data, newline_mask);
        __m128i zeros = _mm_cmpeq_epi8(data, zero_mask);
        __m128i mask = _mm_or_si128(_mm_or_si128(quotes, zeros),                   
             _mm_or_si128(escapes, newlines));
        int m = _mm_movemask_epi8(mask);
        if (m != 0) {
            start += __builtin_ctz(m);

    // Process any remaining bytes (less than 16)
    while (start < end) {
        if (*start == '<' || *start == '&' 
             || *start == '\r' || *start == '\0') {

You can do slightly better if you use an approach we call vectorize classification (see Langdale and Lemire, 2019). Basically, you combine a SIMD approach with vectorized table lookups to classify the characters. The ARM NEON version using two table lookups looks as follows:

void AdvanceStringTable(const char *&start, const char *end) {
  uint8x16_t low_nibble_mask = {0b0001, 0, 0, 0, 0, 0, 0b0100, 
          0, 0, 0, 0, 0, 0b0010, 0b1000, 0, 0};
  uint8x16_t high_nibble_mask = {0b1001, 0, 0b0100, 0b0010, 
          0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
  uint8x16_t v0f = vmovq_n_u8(0xf);
  uint8x16_t bit_mask = {16, 15, 14, 13, 12, 11, 10, 9, 8,
                            7, 6, 5, 4, 3, 2, 1};
  static constexpr auto stride = 16;
  for (; start + (stride - 1) < end; start += stride) {
    uint8x16_t data = vld1q_u8(reinterpret_cast<const uint8_t *>(start));
    uint8x16_t lowpart = vqtbl1q_u8(low_nibble_mask, vandq_u8(data, v0f));
    uint8x16_t highpart = vqtbl1q_u8(high_nibble_mask,  
           vshrq_n_u8(data, 4));
    uint8x16_t classify = vandq_u8(lowpart, highpart);
    uint8x16_t matchesones = vtstq_u8(classify, vdupq_n_u8(0xFF));
    uint8x16_t matches = vandq_u8(bit_mask, matchesones);
    int m = vmaxvq_u8(matches);
    if(m != 0) {
      start += 16 - m;
  for (;start < end; start++) {
    if(*start == '<' || *start == '&' || *start == '\r' 
     || *start == '\0') {

This version is close to Bikineev’s code as it appears in the Google Chrome engine, except that I use standard instrinsics while Google engineers prefer to use the excellent highway SIMD library by Jan Wassenberg.

We can do slightly better in this instance because Bikineev only needs to distinguish between four characters. A single table lookup is needed. We did not elaborate in Langdale and Lemire (2019) but vectorized classification works using one, two, three or more table lookups, depending on the complexity of the target set. The simpler version might look as follows:

void AdvanceStringTableSimpler(const char *&start, const char *end) {
  uint8x16_t low_nibble_mask = {0, 0, 0, 0, 0, 0, 0x26, 0, 0, 
                            0, 0, 0, 0x3c, 0xd, 0, 0};
  uint8x16_t v0f = vmovq_n_u8(0xf);
  uint8x16_t bit_mask = {16, 15, 14, 13, 12, 11, 10, 9, 8,
                            7, 6, 5, 4, 3, 2, 1};
  static constexpr auto stride = 16;
  for (; start + (stride - 1) < end; start += stride) {
    uint8x16_t data = vld1q_u8(reinterpret_cast<const uint8_t *>(start));
    uint8x16_t lowpart = vqtbl1q_u8(low_nibble_mask, vandq_u8(data, v0f));
    uint8x16_t matchesones = vceqq_u8(lowpart, data);
    uint8x16_t matches = vandq_u8(bit_mask, matchesones);
    int m = vmaxvq_u8(matches);
    if(m != 0) {
      start += 16 - m;
  for (;start < end; start++) {
    if(*start == '<' || *start == '&' 
     || *start == '\r' || *start == '\0') {

How do these three techniques compare? I wrote a small benchmark where I scan the HTML of the Google home page. I ran the benchmark on my Apple M2 laptop (LLVM 15).

method speed instructions/byte
naive (scalar) 2.0 GB/s 9.8 instructions/byte
naive (SIMD) 5.8 GB/s 2.1 instructions/byte
vectorized classification (2 lookups) 6.0 GB/s 2.0 instructions/byte
vectorized classification (1 lookup) 6.8 GB/s 1.8 instructions/byte

The results follow my expectations: the simplest vectorized classification routine has the best performance. However, you may observe that even a rather naive SIMD approach can be quite fast in this instance.

If you have an old SSE2 PC, only the simple SIMD approach is available. My results suggest that it might be good enough to get good results.

Quickly checking whether a string needs escaping

In software, we often represent strings by surrounding them with quotes ("). What happens if the string itself contains quotes? We then need to escape the string. For example, the quote character (") or the backslash character (\) should be replaced by \" or \\. Most programmers are familiar with this process.

Most strings do not need to be escaped. It is thus useful to quickly check whether a string requires escaping.

In the popular interchange format JSON, strings must be escaped if they contain the quote character, the backslash character or any ASCII control character (i.e., with a code point less than 32).

How might we check such a string? Let us assume that we are using C++. A reasonable function might look as follows.

bool simple_needs_escaping(std::string_view v) {
  for (char c : v) {
    if ((uint8_t(c) < 32) | (c == '"') | (c == '\\')) {
      return true;
  return false;

The function takes a std::string_view named v as its argument. It iterates over each character c in the input string v. Inside the loop, we first use the comparison
(uint8_t(c) < 32) which checks if the ASCII value of the character is less than 32. This condition covers control characters (such as newline, tab, etc.). Then the comparison (c == '"') checks if the character is a double quote (") and (c == '\\') checks if the character is a backslash (\). If any of the above conditions are true for a character, the function returns true, indicating that the character needs escaping. If none of the conditions are met for any character, the function returns false, indicating that no escaping is needed.

Importantly, this function should exit as soon as a character needing escaping is found. If we expect that no such character will be found, we might try a different approach where we always scan the whole input. This allows the compiler to try other optimizations. In particular, the compiler is more likely to use autovectorization: the ability of our optimizing compiler to compiler our code using fancy instructions like Single Instruction, Multiple Data (SIMD) instructions. I call such a function “branchless” as a reference to the fact that it does not branch out. The result might look as follows:

bool branchless_needs_escaping(std::string_view v) {
  bool b = false;
  for (char c : v) {
    b |= ((uint8_t(c) < 32) | (c == '"') | (c == '\\'));
  return b;

We might also try a variation with table lookups. Instead of doing arithmetic and comparisons, we build a single table containing for all possible byte value whether it requires escaping or not.

It takes bit more effort but the result can be quite fast because each character is checked with a single load from a table, along with maybe or two additional instructions.

static constexpr std::array<uint8_t, 256> json_quotable_character =
    []() constexpr {
  std::array<uint8_t, 256> result{};
  for (int i = 0; i < 32; i++) {
    result[i] = 1;
  for (int i : {'"', '\\'}) {
    result[i] = 1;
  return result;

bool table_needs_escaping(std::string_view view) {
  uint8_t needs = 0;
  for (uint8_t c : view) {
    needs |= json_quotable_character[c];
  return needs;

Can we do better? We might if we use SIMD instructions deliberately such as NEON or SSE2. For the most part, your computer is likely either an ARM machine, supporting at least NEON instructions or an x64 machine supporting at least SSE2 instructions. It is easy to distinguish at compile time between these two scenarios. Of course, your processor might support even fancier instructions, but NEON and SSE2 should be good enough to get a good speedup, especially if the strings are not very long.

A good general strategy is to load the data in blocks of 16 bytes and do a few comparisons over these 16 bytes. The magic of SIMD instructions is that it can do 16 comparisons at once, so it can be much faster than character by character processing. What about the case where we have fewer than 16 characters? If you do not want to read past the string, you can simply fall back on one of our more conventional functions.

The NEON code might look as follows:

bool simd_needs_escaping(std::string_view view) {
  if (view.size() < 16) {
    return simple_needs_escaping(view);
  size_t i = 0;
  static uint8_t rnt_array[16] = {1, 0, 34, 0, 0,  0, 0, 0,
                                  0, 0, 0,  0, 92, 0, 0, 0};
  const uint8x16_t rnt = vld1q_u8(rnt_array);
  uint8x16_t running{0};
  for (; i + 15 < view.size(); i += 16) {
    uint8x16_t word = vld1q_u8((const uint8_t *) + i);
    running = vorrq_u8(
        vceqq_u8(vqtbl1q_u8(rnt, vandq_u8(word, vdupq_n_u8(15))), word));
    running = vorrq_u8(running, vcltq_u8(word, vdupq_n_u8(32)));
  if (i < view.size()) {
    uint8x16_t word =
        vld1q_u8((const uint8_t *) + view.length() - 16);
    running = vorrq_u8(
        vceqq_u8(vqtbl1q_u8(rnt, vandq_u8(word, vdupq_n_u8(15))), word));
    running = vorrq_u8(running, vcltq_u8(word, vdupq_n_u8(32)));
  return vmaxvq_u32(vreinterpretq_u32_u8(running)) != 0;

The SSE2 code might look at follows:

inline bool simd_needs_escaping(std::string_view view) {
  if (view.size() < 16) {
    return simple_needs_escaping(view);
  size_t i = 0;
  __m128i running = _mm_setzero_si128();
  for (; i + 15 < view.size(); i += 16) {
    __m128i word = _mm_loadu_si128((const __m128i *)( + i));
    running = _mm_or_si128(running, _mm_cmpeq_epi8(word, _mm_set1_epi8(34)));
    running = _mm_or_si128(running, _mm_cmpeq_epi8(word, _mm_set1_epi8(92)));
    running = _mm_or_si128(
        running, _mm_cmpeq_epi8(_mm_subs_epu8(word, _mm_set1_epi8(31)),
  if (i < view.size()) {
    __m128i word =
        _mm_loadu_si128((const __m128i *)( + view.length() - 16));
    running = _mm_or_si128(running, _mm_cmpeq_epi8(word, _mm_set1_epi8(34)));
    running = _mm_or_si128(running, _mm_cmpeq_epi8(word, _mm_set1_epi8(92)));
    running = _mm_or_si128(
        running, _mm_cmpeq_epi8(_mm_subs_epu8(word, _mm_set1_epi8(31)),
  return _mm_movemask_epi8(running) != 0;

You can optimize further the SIMD-based functions to reduce the number of instructions, but they already use far fewer when processing  blocks of 16 bytes than conventional functions.

It can be tricky to benchmark such functions. You will find much difference depending on your compiler and your processor. And the results are sensitive to the data, obviously. However my experience is that the SIMD approaches usually win, by a lot. To test it out, I wrote a small benchmark. In my benchmark, I use a few strings, of different lengths. Some of my strings have only a handful of characters, and some are short sentences. I have dozens of strings. None of the strings require escaping: I believe that this is common scenario.

system simple branchless table SIMD
Linux GCC 12, Intel Ice Lake (3.2 GHz) 0.65 GB/s 0.91 GB/s 1.9 GB/s 5.2 GB/s
Linux LLVM 16, Intel Ice Lake (3.2 GHz) 0.91 GB/s 2.6 GB/s 2.5 GB/s 5.7 GB/s

In these results, the table-based approach is quite competitive.  However, it can be beaten by the branchless  approach when using LLVM/clang due to its good ability to autovectorize the code.

Yet, in all instances, the hand-coded SIMD functions are at least twice as fast. As usual, my source code is available and I invite you to run your own benchmarks.

Note: The character with code point value 127 is also a control character in ASCII. Furthermore, Unicode has many control characters.

Never reason from the results of a sampling profiler

In the quest for software optimization, a trusty companion is the sampling profiler, a tool available in most programming languages. These profilers work unobtrusively, taking snapshots of the program’s state and recording the currently executing function or instruction.

While profilers sound like a silver bullet for identifying performance bottlenecks, their usefulness has limitations. They excel at highlighting bottlenecks, but often lack the nuance to pinpoint the root cause. In simpler cases, a profiler’s report might be enough, but relying solely on this data can lead one astray. Misinterpretations of profiling results are a common pitfall I’ve observed amongst programmers.

Imagine a store manager facing customer complaints about long lines. A frustrated customer like myself might be stuck due to a malfunctioning cash register. However, if the manager, instead of fixing the register, simply photographs the queue to identify the “culprit,” I, the innocent bystander, might be wrongly blamed for the delay. Profilers can be just as misleading, highlighting symptoms without revealing the underlying cause.

You are taking a few simple screenshots of a complex system. Of course, you can take more screenshots, and make your screenshots richer, but then you start affecting the system, and falling prey to a software-equivalent Heinsenberg uncertainy principle: you can either know the state of your program very precisely at all times, but then you know little about its speed, or you can measure quite precisely the speed, but with little idea of the intermediate speeds.

Do use sampling profilers. I find them useful. Just do not reason about your problems from them. They merely offer a starting point.

Further reading: Sampling profilers can mislead, and mastering any one tool (e.g., perf or VTune or uPerf) won’t magically confer analysis expertise.

Science and Technology links (May 25 2024)

  1. Artificial intelligence is far more efficient at producing content than human beings, as far as carbon emissions go.
  2. Human brains got larger by over 5% between 1930 and 1970.
  3. Replacing plastics by ‘environment friendly’ alternatives typically results in greater greenhouse gas emissions.
  4. Prostate-specific antigen screening has only a small effect on men’s risk of dying in absolute terms.
  5. Local exposure to poor individuals reduces support for redistribution among the well-off. In other words, wealthy people are more likely to favor government programs helping the poor if they never see poor people.
  6. Happier looking people are judged better. If you want to be viewed as a good person, make sure you appear happy.
  7. Females mount stronger immune responses to many pathogens, they awaken more frequently at night, they express greater concern about physically dangerous stimuli, they exert more effort to avoid social conflicts, they exhibit a personality style more focused on life’s dangers, they react to threats with greater fear, disgust and sadness and they develop more threat-based clinical conditions than males. (Benenson et al.).
  8. The Lincoln sea, the sea North of Greenland, was ice free about 10,000 years ago.
  9. ADHD and autism referrals up fivefold in 2023 in the UK. It is unclear why that is, but over diagnosis is a possibility.
  10. We believe that one of the earliest city might have been in modern-day Turkey, about 9,000 years ago.
  11. About 20,000 years ago, sea levels were over 100 meters lower, as we were in the last glacial maximum.
  12. High-intensity strength training exercises are an effective means to preserve bone density while improving muscle mass, strength, and balance in postmenopausal women.
  13. The average American is willing to pay over 500$ to get a 3-month exemption from a medical mask mandate.
  14. Experiencing nature leads to healthier food choices.
  15. Australia is getting greener, rapidly.
  16. When you lose weight, you spend less energy. However, if you consume relatively more fat or protein during the weight loss, you tend to use more energy.
  17. Trees are getting bigger.
  18. Sun exposure may improve your health.
  19. They are conducting a clinical trial for tooth regrowth technology in Japan.

Learning from the object-oriented mania

Back when I started programming professionally, every expert and every software engineering professor would swear by object-oriented programming. Resistance was futile. History had spoken: the future was object-oriented.

It is hard to understate how strong the mania was. In education, we started calling textbooks and videos ‘learning objects‘. Educators would soon ‘combine learning objects and reuse them‘.

A competitor to a client I was working on at the time had written a server in C. They had to pay lip service to object-oriented programming, so they said that their code was ‘object-oriented.

I once led a project to build an image compression system. They insisted that before we even wrote a single line of code, we planned it out using ‘UML’. It had to be object-oriented from the start, you see.

You had to know your object-oriented design patterns, or you could not be taken seriously.

People rewrote their database engines so that they would be object-oriented.

More than 25 years later, we can finally say, without needing much courage, that it was insane, outrageous, and terribly wasteful. 

Yet, even today, the pressure remains on. Students are compelled to write simple projects using multiple classes. Not just learn the principles of object-oriented programming, which is fair enough, but we still demand that they embrace the ideology.

To be fair, some of the basic principles behind object-oriented programming can be useful. At least, you should know about them.

But the mania was unwarranted and harmful.

The lesson you should draw is not that object-oriented is bad, but rather that whatever is the current trendy technique and trendy idea, is likely grossly overrated.

The social mechanism is constantly in action, though it is no longer acting for object-oriented programming. It takes many forms. Not long ago, you had to wear a mask to attend a conference. Everyone ‘knew’ that masks stopped viruses and had no side-effect… just like everyone just knew that object-oriented programming makes better and more maintainable software, without negative side-effects. All experts agree. All figure of authorities agree. The written press agrees. The celebrities agree. The social pressure to conform is everywhere. It must be true, it has to be true. Anyone disagreeing is a bad person.

You can recognize such a social contagion by its telltale signs.

  1. Rapid Spread: A social contagion spreads quickly through a group or community, much like a wildfire. One day everyone is talking about the latest object-oriented pattern, and the next day, everyone is putting it into practice.
  2. Amplification: You often observe the emergence of ‘influencers’, people who gain high social status and use their newly found position to push further the hype. The object-oriented mania was driven by many key players who made a fortune in the process. They appeared in popular shows, magazines, and so forth.
  3. Peer Influence: Social contagion often relies on peer influence. E.g., everyone around you starts talking about object-oriented programming.
  4. Conformity: People often mimic the behaviors or attitudes of others in their group, leading to a conformity effect. People who do not conform are often excluded, either explicitly or implicitly. For example, object-oriented started to appear in job ads and was promoted by government agencies.
  5. Aggressive Behavior: You see a significant change from usual behavior as irrationality creeps in. If you criticize object-oriented programming, something is wrong with you!
  6. Grandiose Beliefs or Delusions: Claims that object-oriented programming would forever change the software industry for the better were everywhere. You could just easily reuse your objects and classes from one project to the other. Never mind that none of these claims could ever be sustained.
  7. Risky Behavior: Entire businesses bet their capital on projects trying to reinvent some established tool in an object-oriented manner. People kept throwing caution to the wind: let us rebuild everything the one true way, what is the worse that can happen?

Appendix. There is a very good reason why hardly any of us wears a mask today. If masks prevented the transmission of respiratory diseases, it would have been a medical breakthrough. But they do no such thing. There is no evidence that masks have benefits and they may well create net harm. The one European country that did not embrace general mask mandates (Sweden) ended up with effectively the lowest excess mortality in Europe.

Cochrane conducted a thorough review of all the strong evidence gathered during the covid era. Here is what the Cochrane review conclude:

We included 12 trials (10 cluster‐RCTs) comparing medical/surgical masks versus no masks to prevent the spread of viral respiratory illness (two trials with healthcare workers and 10 in the community). Wearing masks in the community probably makes little or no difference to the outcome of influenza‐like illness (ILI)/COVID‐19 like illness compared to not wearing masks. Wearing masks in the community probably makes little or no difference to the outcome of laboratory‐confirmed influenza/SARS‐CoV‐2 compared to not wearing masks. Harms were rarely measured and poorly reported.

Here are the results from an earlier Cochrane review, based on pre-COVID studies:

Compared with wearing medical or surgical masks, wearing N95/P2 respirators probably makes little to no difference in how many people have confirmed flu; and may make little to no difference in how many people catch a flu-like illness.

Ian Miller wrote a fantastic book on the topic: Unmasked: The Global Failure of COVID Mask Mandates.

Atlas et al. (2024) included masks in their lessons to draw from the covid era: Masks Were of Little or No Value and Possibly Harmful.

German officials admitted that evidence for making masks mandatory was lacking, according to health agency’s deliberations released after long legal battle.

Sandlund et al. conclude:

Because benefits of masking for COVID-19 have not been identified, it should be recognised that mask recommendations for children are not supported by scientific evidence.

Forwarding references in C++

In C++, there are different ways to pass a value to a function. Typically, at any given time, an object in C++ ‘belongs’ to a single function. The various ways to call a function differ in who owns the object, the caller or the callee (the function being called).

The simplest one is that we pass by value. In such cases, a copy is typically made of the object and both the caller and the callee own a copy.

void value(MyClass obj) {}

We can pass by reference. You recognize a reference by the single ampersand (&). The caller owns the object, but the callee gets access to it.

void reference(MyClass& obj) {}

You can also pass by an “rvalue reference” which you recognize by the ‘&&’ symbols. In such cases while the caller initially creates the object, but its ownership is passed to the callee. I personally dislike the expression ‘rvalue reference’ and I would have preferred something less technical.

void rvalue_reference(MyClass&& obj) {}

However, in some instances, you do not care whether your function gets to own the value, or has merely a reference to it. Writing two functions duplicates the code. Instead, you can then use a forwarding reference:

template <typename T>
void forwarding_reference(T&& obj) {}

It looks like an rvalue reference, but it is not: it can be either a normal reference or an rvalue reference depending on how you call it.

Here is how you might call these functions in practice:

MyClass obj;

The following table is a summary. A forwarding reference might be either a regular reference or an rvalue reference depending on how it is called.

caller owns? callee owns?
by value yes yes
by reference (&) yes no
by rvalue reference (&&) no yes

Peer review is not the gold standard in science

Peer review as we know it today was introduced very late, over a century after the scientific revolution. It happened after Einstein’s time… arguably the most productive era in science. Current scientists often equate a success with the publication in a selective peer-reviewed venue. But that was never the scientific paradigm. In fact, it is pre-scientific thinking. Back in Einstein’s time, many scientists believed in the ether. It would have been difficult to dismiss the ether as a concept. The prudent approach would have been to pay lip service to the ether. Similarly, most scientists believed in eugenics. They believed in forced sterilization for the greater good. Many of the racist laws in the US followed straight from progressive science. Opposing eugenics would have been difficult in the context of peer review. It would have been difficult to challenge eugenics openly as a scientists.

Siler et al. (2014) looked at published manuscripts that were initially rejected. They find:

Of the 808 eventually published articles in our dataset, our three focal journals rejected many highly cited manuscripts, including the 14 most popular; roughly the top 2 percent. Of those 14 articles, 12 were desk-rejected. This finding raises concerns regarding whether peer review is ill-suited to recognize and gestate the most impactful ideas and research.

Recently, people like Matt Ridley challenged the idea that the SARS-Cov2 virus originated from nature. Back when he published his book on the topic, it would have been difficult to pass peer review.

You may not remember, but early on, it would widely accepted that the lab origin of SARS-Cov2 was only for far-right conspiracy theorists. The Canadian State broadcaster (CBC) told us, in its ‘science’ section:

One of the most persistent and widespread pieces of disinformation during the COVID-19 pandemic has been the conspiracy theory that the novel coronavirus that causes the disease was created in a lab — and was let loose either by accident or on purpose by some nefarious actor.

In the US Senator Cotton suggested that thespread of a coronavirus is connected to research at the Wuhan institute of virology. In response, the Washington Post wrote:

Sen. Tom Cotton (R-Ark.) keeps repeating a coronavirus conspiracy theory that was already debunked. (…) In response to Cotton’s remarks, as well as in previous interviews with The Washington Post, numerous experts dismissed the possibility the coronavirus may be man-made.

Here is what one of the most reputed medical journal (The Lancet) published:

We stand together to strongly condemn conspiracy theories suggesting that COVID-19 does not have a natural origin.

The article omits the fact that the authors have glaring conflicts of interest (undisclosed).

Thacker describes some of the event in a piece for BMJ:

But the effort to brand serious consideration of a lab leak a “conspiracy theory” only ramped up. Filippa Lentzos, codirector of the Centre for Science and Security Studies at King’s College, London, told the Wall Street Journal, “Some of the scientists in this area very quickly closed ranks.” She added, “There were people that did not talk about this, because they feared for their careers. They feared for their grants.

Daszak had support. After he wrote an essay for the Guardian in June 2020 attacking the former head of MI6 for saying that the pandemic could have “started as an accident,” Jeremy Farrar, director of the Wellcome Trust [a major funder] and co-signer of the Lancet letter, promoted Daszak’s essay on Twitter, saying that Daszak was “always worth reading.”

Daszak’s behind-the-scenes role in orchestrating the statement in the Lancet came to light in November 2020 in emails obtained through freedom of information requests by the watchdog group US Right To Know.

“Please note that this statement will not have EcoHealth Alliance logo on it and will not be identifiable as coming from any one organization or person,” wrote Daszak in a February email, while sending around a draft of the statement for signatories. In another email, Daszak considered removing his name from the statement “so it has some distance from us and therefore doesn’t work in a counterproductive way.”

Several of the 27 scientists who signed the letter Daszak circulated did so using other professional affiliations and omitted reporting their ties to EcoHealth Alliance.

For Richard Ebright, professor of molecular biology at Rutgers University in New Jersey and a biosafety expert, scientific journals were complicit in helping to shout down any mention of a lab leak. “That means Nature, Science, and the Lancet,” he says. In recent months he and dozens of academics have signed several open letters rejecting conspiracy theory accusations and calling for an open investigation of the pandemic’s origins.

Efforts to characterise the lab leak scenario as unworthy of serious consideration were far reaching, sometimes affecting reporting that had first appeared well before the covid-19 pandemic. For example, in March 2020 Nature Medicine added an editor’s note (“Scientists believe that an animal is the most likely source of the coronavirus”) to a 2015 paper on the creation of a hybrid version of a SARS virus, co-written by Shi.

Here are the facts as we knew them back then… as anyone could know…

  • There was an outbreak caused by a bat sarbecovirus, in the one city in the world that had been collecting hundreds of bat sarbecoviruses and experimenting on them.
  • It happened one year after that lab proposed inserting the one feature that distinguishes SARS‑CoV‑2 from all other viruses.
  • The lab in question refuses to this day to release the database of the viruses it had been working on.
  • Virus leaks have been common.

It was always sensible to ask whether SARS-CoV-2 came from the Wuhan lab. Yet this was openly censored. As is often the case, instead of reflecting on this failure, many people rewrite history. “We never denied it could have come from a lab”, they say. “We never denied that it could have been human-made,” they say. But they very explicitly and strongly did so. They specifically and repeatedly said that this virus could not have been made in a laboratory:  yet a funding application to do exactly that, a few years before, had been submitted to the US government by Daszak, the very man who insisted that the lab origin was a conspiracy theory.

Of course, knowledgeable scientists knew that the lab origin was a possibility. They did not dare to speak up. Would you speak up when it could mean the end of your career?

This was not at all an isolated incident. Dr. Scott Atlas was censored by Stanford for questioning the covid dogma. The Stanford Review writes:

This censure, now a black mark on the University, was unquestionably motivated by political animosity. Atlas, a health policy expert who worked as a professor at Stanford Medical School for fourteen years, chose to serve his country by taking an advisory role in the Trump Administration’s White House Coronavirus Task Force. As an advisor, Atlas suggested reopening schools and businesses and pushed back against draconian lockdown policies.

You might answer… « Attacking people for getting closer to the truth isn’t new » But science seeks to address this very point. In fact, it is the very essence of the epistemology of science: the recognition that truth is not arrived by social consensus or by following the powerful. There are many ways to describe science, but to a first approximation…  Science is the process whereas anyone can post ideas and results for others to replicate, and everyone get to fail in public, and, hopefully correct themselves. Science the opposite of a gatekeeping process, it is, by its very nature, a progressive and open process.

It does not mean you should not use peer review publication. But you need to recognize that it is not the reference in science. Evidence is evidence. Consensus is not evidence.

Remember: ‘The reasonable man adapts himself to the world; the unreasonable man persists in trying to adapt the world to himself. Therefore all progress depends on the unreasonable man.’

How fast can you construct a small list of strings in C for Python?

Python is probably the most popular programming language in the world right now. Python is easy to extend using C code.

You may want to return from Python a small data structure. When crossing from C to Python, there is an overhead. Thus, if performance is a concern, you do not want to return lots of small values such as hundreds of individual small strings.

However, you may want to return a list of strings such as

['zero elephant', 'one elephant is having fun', 'two elephants are having fun',
'three elephants are meeting with the president', 'four elephants',
'five elephants in an hexagon', 'six elephants are playing the saxophone',
'seven elephants are visiting the school', 'eight elephants are at Church',
'nine elephants are having a party']

I am going to assume that these strings are in an array called ‘numbers’ in my C code. Of course, if the strings are known at compile time, I could just precompute the array and return it. However, I want to generate the content dynamically.

A reasonable C function which will return an list is as follows:

PyObject* all_strings(PyObject* self) {
  size_t len = sizeof(numbers) / sizeof(numbers[0]);
  PyObject* pyList = PyList_New(len);
  for (size_t i = 0; i < len; ++i) {
    PyObject* pyString = PyUnicode_FromString(numbers[i]);
    PyList_SET_ITEM(pyList, i, pyString);
  return pyList;

It looks a bit complicated, but it is not. It is just an application of the Python C functions. The key element is the PyUnicode_FromString function which automatically takes a pointer to an UTF-8 string, and converts it into a Python string. In our case, all our strings are ASCII, so the function does more work than needed. In this instance, I know ahead of time the size of the list (hence PyList_New(len)), but I could also have constructed an empty list (PyList_New(0)) and appended strings to it as needed.

Can we do better? We might. Python introduced lower-level string construction functions. You start by constructing a string that cannot be resized, and you must tell it whether the string content fits in one byte (ASCII or Latin1), or whether it requires more storage per character (UTF-16 without surrogate pairs) or whether you need the full Unicode range. In my case, it is easy: my strings are pure ASCII. In the general case, you would need to ascertain the string type (a functionality we plan to add to the simdutf library).

The code becomes slightly more complicated, but barely so…

PyObject* all_strings_new(PyObject* self) {
  size_t len = sizeof(numbers) / sizeof(numbers[0]);
  PyObject* pyList = PyList_New(len);
  for (size_t i = 0; i < len; ++i) {
    const char * str = numbers[i];
    size_t len = strlen(str);
    PyObject* py_string = PyUnicode_New(len, 127);
    Py_UCS1* data = PyUnicode_1BYTE_DATA(py_string);
    memcpy(data, str, len);
    PyList_SET_ITEM(pyList, i, py_string);
  return pyList;

I wrote a small benchmark. You need Python and a development environment to build it. I ran the benchmark on my Apple M2 laptop, using LLVM 15 and Python 3.12. Your results will vary.

In my case, I get a very significant boost (2x) from the lower-level approach.

basic 270 ns/structure
lower-level 140 ns/structure

My data structure contains 295 bytes of strings, so the lower-level approach generates strings at over 2 GB/s, whereas the conventional approach has half the speed.

Should Node.js be built with ClangCL under Windows?

Under Windows, when using Visual Studio to build C++ code, there are two possible compiler strategies. The Visual Studio compiler (often referred to as MSVC) is the default compiler provided by Microsoft for Windows development. In Debug mode, the regular Visual Studio compiler produces faster compilation times and more performant code compared to ClangCL. ClangCL is part of the Clang/LLVM project, which is an open-source compiler toolchain. ClangCL is compatible with the Visual Studio runtime and links with the Microsoft implementation of the Standard Library. It’s available as an optional component in Visual Studio 2019 and later versions.

In Debug mode, I find that the regular Visual Studio compiler builds faster. However, in release mode, I found empirically that ClangCL approach may provide more performant code. On some micro-benchmarks, the difference can be large (e.g., 40%) although I expect more modest gains on complex systems.

As of Chrome 64, Google Chrome for Windows is compiled with ClangCL. Thus Clang is now used to build Chrome for all platforms it runs on, including macOS, iOS, Linux, Chrome OS, Android, and Windows. Firefox switched to ClangCL in 2018. And at least some game developers have adopted ClangCL.

Node.js is an open-source, cross-platform JavaScript runtime environment. It allows developers to execute JavaScript code outside of a web browser. Unlike traditional JavaScript, which primarily runs in browsers, Node.js enables server-side execution of JavaScript. Node.js is part of popular web development stacks Node.js relies on the Google Chrome V8 JavaScript Engine: Node.js is built on the V8 JavaScript engine, the same engine used by Google Chrome.

Node.js is built under Windows using the regular Visual Studio compiler. Thanks in large part to Michaël Zasso, it is possible to build the Node.js under Windows with ClangCL. Could it improve the performance?

To start answering this question, I ran the standard V8 benchmarks from Node.js. These benchmarks mostly focus on V8 performance and are not affected by changes in other components. For my tests, I use Visual Studio 2022 on Microsoft Surface Laptop Studio.

All results point at improvements. That is, on average, the speed is greater with ClangCL than using the standard Visual Studio compiler. However, there is much noise in my numbers. Using the V8 benchmarks, only one test was statistically strong (serialize.js len=256).

function improvement
v8\get-stats getHeapSpaceStatistics 3% +/- 11%
v8\get-stats getHeapStatistics 10% +/- 11%
v8\serialize.js len=256 6% +/- 2%
v8\serialize.js len=16384 2% +/- 2%
v8\serialize.js len=524288 19% +/- 50%

I should stress that compilers have strengths and weaknesses. The regular Visual Studio compiler is perfectly capable and you should expect it to do better in some instances. And Microsoft have some of the best compiler engineers in the world: each new version might bring in improvements.

Furthermore, some tasks and benchmarks are not necessarily affected by the choice of a compiler: e.g., a network access, a disk processing routine, or a memory allocation stress test.

Yet it appears that there might be benefits to a transition to ClangCL for Node.js.

Careful with Pair-of-Registers instructions on Apple Silicon

Egor Bogatov is an engineer working on C# compiler technology at Microsoft. He had an intriguing remark about a performance regression on Apple hardware following what appears to be an optimization. The .NET 9.0 runtime introduced the optimization where two loads (ldr) could be combined into a single load (ldp). It is a typical peephole optimization. Yet it made things much slower in some cases.

Under ARM, the ldr instruction is used to load a single value from memory into a register. It operates on a single register at a time. Its assembly syntax is straightforward ldr Rd, [Rn, #offset]. The ldp instruction (Load Pair of Registers) loads two consecutive values from memory into two registers simultaneously. Its assembly syntax is similar but there are two destination registers: ldp Rd1, Rd2, [Rn, #offset]. The ldp instruction loads two 32-bit words or two 64-bit words from memory, and writes them to two registers.

Given a choice, it seems that you should prefer the ldp instruction. After all, it is a single instruction. But there is a catch on Apple silicon: if you are loading data from a memory that was just written to, there might be a significant penalty to ldp.

To illustrate, let us consider the case where we write and load two values repeatedly using two loads and two stores:

for (int i = 0; i < 1000000000; i++) {
  int tmp1, tmp2;
  __asm__ volatile("ldr %w0, [%2]\n"
                   "ldr %w1, [%2, #4]\n"
                   "str %w0, [%2]\n"
                   "str %w1, [%2, #4]\n"
    : "=&r"(tmp1), "=&r"(tmp2) : "r"(ptr):);

Next, let us consider an optimized approach where we combine the two loads into a single one:

for (int i = 0; i < 1000000000; i++) {
  int tmp1, tmp2;
  __asm__ volatile("ldp %w0, %w1, [%2]\n"
                   "str %w0, [%2]\n"
                   "str %w1, [%2, #4]\n"
    : "=&r"(tmp1), "=&r"(tmp2) : "r"(ptr) :);

It would be surprising if this new version was slower, but it can be. The code for the benchmark is available. I benchmarked both on AWS using Amazon’s graviton 3 processors, and on Apple M2. Your results will vary.

function graviton 3 Apple M2
2 loads, 2 stores 2.2 ms/loop 0.68 ms/loop
1 load, 2 stores 1.6 ms/loop 1.6 ms/loop

I have no particular insight as to why it might be, but my guess is that Apple Silicon has a Store-to-Load forwarding optimization that does not work with Pair-Of-Registers loads and stores.

There is an Apple Silicon CPU Optimization Guide which might provide better insight.

Large language models (e.g., ChatGPT) as research assistants

Software can beat human beings at most games… from Chess to Go, and even poker. Large language models like GPT-4 offered through services such as ChatGPT allow us to solve a new breed of problems. GPT-4 can beat 90% of human beings at the bar exam. Artificial intelligence can match math Olympians.

The primary skills of academics are language-related: synthesis, analogy, extrapolation, etc. Academics analyze the literature, identify gaps, and formulate research questions. They review and synthesize existing research. They write research papers, grant proposals, and reports. Being able to produce well-structured and grammatically correct prose is a vital skill for academics.

Unsurprisingly, software and artificial intelligence can help academics, and maybe replace them in some cases. Liang et al. found that an increasing number of research papers are written with tools like GPT-4 (up to 18% in some fields). It is quite certain that in the near future, a majority of all research papers will be written with the help of artificial intelligence. I suspect that they will be reviewed with artificial intelligence as well. We might soon face a closed loop where software writes papers while other software reviews it.

I encourage scholars to apply artificial intelligence immediately for tasks such as…

  1. Querying a document. A tool like BingChat from Microsoft allows you to open a PDF document and query it. You may ask “what are the main findings of this study?” or “are there any practical applications for this work?”.
  2. Improve text. Many academics, like myself, use English as a second language. Of course, large language models can translate, but they can also improve your wording. It is more than a mere grammar checker: it can rewrite part of your text, correcting bad usages as it goes.
  3. Idea generation. I used to spend a lot of time chatting with colleagues about a vague idea I had. “How could we check whether X is true?” A tool like ChatGPT can help you get started. If you ask how to design an experiment to check a given hypothesis, it can often do a surprisingly good job.
  4. Grant applications. You can use tools like ChatGTP to help you with grant applications. Ask it to make up short-term and long-term objectives, sketch a methodology and discuss the impact of your work… it will come up with something credible right away. It is likely that thousands of grant applications have been written with artificial intelligence.
  5. Writing code. You are not much of a programmer, but you want an R script that will load data from your Excel spreadsheet and do some statistical analysis? ChatGPT will do it for you.
  6. Find reviewers and journals. Sometimes you have done some work and you would like help picking the right journal, a tool like ChatGPT can help. If a student of yours finished their thesis, ChatGPT can help you identify prospective referees.

I suspect that much academic work will soon greatly benefit from artificial intelligence to the point where a few academics will be able to do the work that required an entire research institute in the past.

And this new technology should make mediocre academics even less useful, relatively speaking. If artificial intelligence can write credible papers and grant applications, what is the worth of someone who can barely do these things?

You would think that these technological advances should accelerate progress. But, as argued by Patrick Collison and Michael Nielsen, science productivity has been falling despite all our technological progress. Physics is not advancing faster today than it did in the first half of the XXth century. It may even be stagnant in relative terms. I do not think that we should hastily conclude that ChatGPT will somehow accelerate the rate of progress in Physics. As Clusmann et al. point out:  it may simply ease scientific misconduct. We could soon be drowning in a sea of automatically generated documents. Messeri and Crockett put it elegantly:

AI tools in science risks introducing a phase of scientific enquiry in which we produce more but understand less

Yet there are reasons to be optimistic. By allowing a small group of researchers to be highly productive, by freeing them to explore further with less funding, we could be on the verge of entering into a new era of scientific progress. However, it may not be directly measurable using our conventional tools. It may not appear as more highly cited papers or through large grants. A good illustration is Hugging Face, a site where thousands of engineers from all over the world explore new artificial-intelligence models. This type of work is undeniably scientific research: we have metrics, hypotheses, testing, reproducibility, etc. However, it does not look like ‘academic work’.

In any case, conventional academics will be increasingly challenged. Ironically, plumbers and electricians won’t be so easily replaced, a fact sometimes attributed to the Moravec paradox. Steven Pinker wrote in 1994 that cooks and gardeners are secured in their jobs for decades to come, unlike stock market analysis and engineers. But I suspect that the principle even extends within the academy: some work, like conducting actual experiments, is harder to automate than producing and running models. The theoretical work is likely more impacted by intelligence artificial than more applied, concrete work.

Note: This blog post was not written with artificial intelligence. Expect typos and grammatical mistakes.

How do you recognize an expert?

Go back to the roots: experience. An expert is someone who has repeatedly solved the concrete problem you are encountering. If your toilet leaks, an experienced plumber is an expert. An expert has a track record and has had to face the consequences of their work. Failing is part of what makes an expert: any expert should have stories about how things went wrong.

I associate the word expert with ‘the problem’ because we know that expertise does not transfer well: a plumber does not necessarily make a good electrician. And within plumbing, there are problems that only some plumbers should solve. Furthermore, you cannot abstract a problem: you can study fluid mechanics all you want, but it won’t turn you into an expert plumber.

That’s one reason why employers ask for relevant experience: they seek expertise they can rely on. It is sometimes difficult to acquire expertise in an academic or bureaucratic setting because the problems are distant or abstract. Your experience may not translate well into practice. Sadly we live in a society where we often lose track of and undervalue genuine expertise… thus you may take software programming classes from people who never built software or civil engineering classes from people who never worked on infrastructure projects.

So… how do you become an expert? Work on real problems. Do not fall for reverse causation: if all experts dress in white, dressing in white won’t turn you into an expert. Listening to the expert is not going to turn you into an expert. Lectures and videos can be inspiring but they don’t build your expertise. Getting a job with a company that has real problems, or running your own business… that’s how you acquire experience and expertise.

Why would you want to when you can make a good living otherwise, without the hard work of solving real problems? Actual expertise is capital that can survive a market crash or a political crisis. After Germany’s defeat in 1945… many of the aerospace experts went to work for the American government. Relevant expertise is robust capital.

Why won’t everyone seek genuine expertise? Because there is a strong countervailing force: showing a total lack of practical skill is a status signal. Wearing a tie shows that you don’t need to work with your hands.

But again: don’t fall for reverse causality… broadcasting that you don’t have useful skills might be fun if you are already of high status… but if not, it may not grant you a higher status.

And status games without a solid foundation might lead to anxiety. If you can get stuff done, if you can fix problems, you don’t need to worry so much about what people say about you. You may not like the color of the shoes of your plumber, but you won’t snob him over it.

So get expertise and maintain it. You are likely to become more confident and happier.

How quickly can you break a long string into lines?

Suppose that you receive a long string and you need to break it down into lines. Consider the simplified problems where you need to break the string into segments of (say) 72 characters. It is a relevant problem if your string is a base64 string or a Fortran formatted statement.

The problem could be a bit complicated because you might need consider the syntax. So the speed of breaking into a new line every 72 characters irrespective of the content provides an upper bound on the performance of breaking content into lines.

The most obvious algorithm could be to copy the content, line by line:

void break_lines(char *out, const char *in, size_t length,
  size_t line_length) {
  size_t j = 0;
  size_t i = 0;
  for (; i + line_length <= length; i += line_length) {
    memcpy(out + j, in + i, line_length);
    out[j+line_length] = '\n';
    j += line_length + 1;
  if (i < length) {
    memcpy(out + j, in + i, length - i);

Copying data in blocks in usually quite fast unless you are unlucky and you trigger aliasing. However, allocating a whole new buffer could be wasteful, especially if you only need to extend the current buffer by a few bytes.

A better option could thus be to do the work in-place. The difficulty is that if you load the data from the current array, and then write it a bit further away, you might be overwriting the data you need to load next. A solution is to proceed in reverse: start from the end… move what would be the last line off by a few bytes, then move the second last line and so forth. Your code might look like the following C function:

void break_lines_inplace(char *in, size_t length, size_t line_length) {
  size_t left = length % line_length;
  size_t i = length - left;
  size_t j = length + length / line_length - left;
  memmove(in + j, in + i, left);
  while (i >= line_length) {
    i -= line_length;
    j -= line_length + 1;
    memmove(in + j, in + i, line_length);
    in[j+line_length] = '\n';

I wrote a benchmark. I report the results only for a 64KB input. Importantly, my numbers do not include memory allocation which is separate.

A potentially important factor is whether we allow function inlining: without inlining, the compiler does not know the line length at compile-time and cannot optimize accordingly.

Your results will vary, but here are my own results:

method Intel Ice Lake, GCC 12 Apple M2, LLVM 14
memcpy 43 GB/s 70 GB/s
copy 25 GB/s 40 GB/s
copy (no inline) 25 GB/s 37 GB/s
in-place 25 GB/s 38 GB/s
in-place (no inline) 25 GB/s 38 GB/s

In my case, it does not matter whether we do the computation in-place or not. The in-place approach generates more instructions but we are not limited by the number of instructions.

At least in my results, I do not see a large effect from inlining. In fact, for the in-place routine, there appears to be no effect whatsoever.

Roughly speaking, I achieve a bit more than half the speed as that of a memory copy. We might be limited by the number of loads and stores. There might be a clever way to close the gap.

Science and Technology links (April 13 2024)

      1. Our computer hardware exchange data using a standard called PCI Express. Your disk, your network and your GPU are limited by what PCI Express can do. Currently, it means that you are limited to a few gigabytes per second of bandwidth. PCI Express is about to receive a big performance boost in 2025 when PCI Express 7 comes out: it will support bandwidth of up to 512 GB/s. That is really, really fast. It does not follow that your disks and graphics are going to improve very soon, but it provides the foundation for future breakthroughs.
      2. Sperm counts are down everywhere and the trend is showing no sign of slowing down. There are indications that it could be related to the rise in obesity.
      3. A research paper by Burke et al. used a model to predict that climate change could reduce world GPD (the size of the economy) by 23%. For reference, world GDP grows at a rate of about 3% a year (+/- 1%) so that a cost of 23% is about equivalent to 7 to 8 years without growth. It is much higher than prior predictions. Barket (2024) questions these results:

        It is a complicated paper that makes strong claims. The authors use thousands of lines of code to run regressions containing over 500 variables to test a nonlinear model of temperature and growth for 166 countries and forecast economic growth out to the year 2100. Careful analysis of their work shows that they bury inconvenient results, use misleading charts to confuse readers, and fail to report obvious robustness checks. Simulations suggest that the statistical significance of their results is inflated. Continued economic growth at levels similar to what the world has experienced in recent years would increase the level of future economic activity by far more than Nordhaus’ (2018) estimate of the effect of warming on future world GDP. If warming does not affect the rate of economic growth, then the world is likely to be much richer in the future, with or without warming temperatures.

      4. The firm McKinsey reports finding statistically significant positive relations between the industry-adjusted earnings and the racial/ethnic diversity of their executives. Green and Hand (2024) fail to reproduce these results. They conclude: despite the imprimatur given to McKinsey’s studies, their results should not be relied on to support the view that US publicly traded firms can expect to deliver improved financial performance if they increase the racial/ethnic diversity of their executives.
      5. Corinth and Larrimore (2024) find that after adjusting for hours worked, Generation X and Millennials experienced a greater intergenerational increase in real market income than baby boomers.

Greatest common divisor, the extended Euclidean algorithm, and speed!

We sometimes need to find the greatest common divisor between two integers in software. The fastest way to compute the greatest common divisor might be the binary Euclidean algorithm. In C++20, it can be implemented generically as follows:

template <typename int_type>
int_type binary_gcd(int_type u, int_type v) {
  if (u == 0) { return v; }
  if (v == 0) { return u; }
  auto shift = std::countr_zero(u | v);
  u >>= std::countr_zero(u);
  do {
   v >>= std::countr_zero(v);
   if (u > v) { std::swap(u, v); }
   v = v - u;
  } while (v != 0);
  return u << shift;

The std::countr_zero function computes the “number of trailing zeroes” in an integer. A key insight is that this function often translates into a single instruction on modern hardware.

Its computational complexity is the number of bits in the largest of the two integers.

There are many variations that might be more efficient. I like an approach proposed by Paolo Bonzini which is simpler as it avoid the swap:

int_type binary_gcd_noswap(int_type u, int_type v) {
  if (u == 0) { return v; }
  if (v == 0) { return u; }
  auto shift = std::countr_zero(u | v);
  u >>= std::countr_zero(u);
  do {
   int_type t = v >> std::countr_zero(v);
   if (u > t) v = u - t, u = t;
   else v = t - u;
  } while (v != 0);
  return u << shift;

The binary Euclidean algorithm is typically faster than the textbook Euclidean algorithm which has to do divisions (a slow operation), although the resulting code is pleasantly short:

template <typename int_type>
int_type naive_gcd(int_type u, int_type v) {
  return (u % v) == 0 ? v : naive_gcd(v, u % v);

There are cases where the naive GCD algorithm is faster. For example, if v divides u, which is always the case when v is 1, then the naive algorithm returns immediately whereas the binary GCD algorithm might require many steps if u is large.

To balance the result, we can use a hybrid approach where we first use a division, as in the conventional Euclidean algorithm, and then switch to the binary approach:

template <class int_type> 
int_type hybrid_binary_gcd(int_type u, int_type v) {
  if (u < v) { std::swap(u, v); }
  if (v == 0) { return u; }
  u %= v;
  if (u == 0) { return v; }
  auto zu = std::countr_zero(u);
  auto zv = std::countr_zero(v);
  auto shift = std::min(zu, zv);
  u >>= zu;
  v >>= zv;
  do {
    int_type u_minus_v = u - v;
    if (u > v) { u = v, v = u_minus_v; }
    else {v = v - u; }
    v >>= std::countr_zero(u_minus_v);
  } while (v != 0);
  return u << shift;

I found interesting that there is a now a std::gcd function in the C++ standard library so you may not want to implement your own greatest-common-divisor if you are programming in modern C++.

For the mathematically inclined, there is also an extended Euclidean algorithm. It also computes the greatest common divisor, but also the Bézout coefficients. That is, given two integers a and b, it finds integers x and y such that x * a + y * b = gcd(a,b). I must admit that I never had any need for the extended Euclidean algorithm. Wikipedia says that it is useful to find multiplicative inverses in a module space, but the only multiplicative inverses I ever needed were computed with a fast Newton algorithm. Nevertheless, we might implement it as follows:

template <typename int_type> struct bezout {
  int_type gcd;
  int_type x;
  int_type y;

// computes the greatest common divisor between a and b,
// as well as the Bézout coefficients x and y such as
// a*x + b*y = gcd(a,b)
template <typename int_type>
bezout<int_type> extended_gcd(int_type u, int_type v) {
  std::pair<int_type, int_type> r = {u, v};
  std::pair<int_type, int_type> s = {1, 0};
  std::pair<int_type, int_type> t = {0, 1};
  while (r.second != 0) {
    auto quotient = r.first / r.second;
    r = {r.second, r.first - quotient * r.second};
    s = {s.second, s.first - quotient * s.second};
    t = {t.second, t.first - quotient * t.second};
  return {r.first, s.first, t.first};

There is also a binary version of the extended Euclidean algorithm although it is quite a bit more involved and it is not clear that it is can be implemented at high speed, leveraging fast instructions, when working on integers that fit in general-purpose registers. It is may beneficial when working with big integers. I am not going to reproduce my implementation, but it is available in my software repository.

To compare these functions, I decided to benchmark them over random 64-bit integers. I found interesting that the majority of pairs of random integers (about two thirds) were coprime, meaning that their greatest common divisor is 1. Mathematically, we would expect the ratio to be 6/pi2 which is about right empirically. At least some had non-trivial greatest common divisors (e.g., 42954).

Computing the greatest common divisor takes hundreds of instructions and hundreds of CPU cycle. If you somehow need to do it often, it could be a bottleneck.

I find that the std::gcd implementation which is part of the GCC C++ library under Linux is about as fast as the binary Euclidean function I presented. I have not looked at the implementation, but I assume that it might be well designed. The version that is present on the C++ library present on macOS (libc++) appears to be the naive implementation. Thus there is an opportunity to improve the lib++ implementation.

The extended Euclidean-algorithm implementation runs at about the same speed as a naive regular Euclidean-algorithm implementation, which is what you would expect. My implementation of the binary extended Euclidean algorithm is quite a bit slower and not recommended. I expect that it should be possible to optimize it further.

function GCC 12 + Intel Ice Lake Apple LLVM + M2
std::gcd 7.2 million/s 7.8 million/s
binary 7.7 million/s 12 million/s
binary (no swap) 9.2 million/s 14 million/s
hybrid binary 12 million/s 17 million/s
extended 2.9 million/s 7.8 million/s
binary ext. 0.7 million/s 2.9 million/s

It may seem surprising that the extended Euclidean algorithm runs at the same speed as std::gcd on some systems, despite the fact that it appears to do more work. However, the computation of the Bézout coefficient along with the greatest common divisor is not a critical path, and can be folded in with the rest of the computation on a superscalar processor… so the result is expected.

My source code is available.

As part of the preparation of this blog post, I had initially tried writing a C++ module. It worked quite well on my MacBook. However, it fell part under Linux with GCC, so I reverted it back. I was quite happy at how using modules made the code simpler, but it is not yet sufficiently portable.

Credit: Thanks to Harold Aptroot for a remark about the probability of two random integers being prime.

Further reading: The libc++ library might update its std::gcd implementation.

A simple algorithm to compute the square root of an integer, byte by byte

A reader asked me for some help in computing (1 – sqrt(0.5)) to an arbitrary precision, from scratch. A simpler but equivalent problem is to compute the square root of an integer (e.g., 2). There are many sophisticated algorithms for such problems, but we want something relatively simple. We’d like to compute the square root bit by bit…

For example, the square root of two is…

  1. 5 / 4
  2. 11 / 8
  3. 22 / 16
  4. 45 / 32
  5. 90 / 64
  6. 181 / 128

More practically, 8-bit by 8-bit, we may want to compute it byte by byte…

  1. 362 / 256
  2. 92681 / 65536
  3. 23726566 / 16777216

How can we do so?

Intuitively, you could compute the integer part of the answer by starting with 0 and incrementing a counter like so:

x1 = 0
while (x1+1)**2 <= M:
  x1 += 1

Indeed, the square of the integer part cannot be larger than the desired power.

You can repeat the same idea with the fractional part… writing the answer as x1+x2/B+... smaller terms.

x2 = 0
while (x1*B + x2 + 1)**2 <= M*B**2:
  x2 += 1

It will work, but it involves squaring ever larger numbers. That is inefficient.

We don’t actually need to compute powers when iterating. If you need to compute x**2, (x+1)**2, (x+2)**2, etc. You can instead use a recursion: if you have computed (x+n)**2 and you need the next power, you just need to add 2(x+n) + 1 because that’s the value of (x+n+1)**2 (x+n)**2.

Finally, we get the following routine (written in Python). I left the asserts in place to make the code easier to understand:

B = 2**8 # or any other basis like 2 or 10
x = 0
power = 0
limit = M
for i in range(10): # 10 is the number of digits you want
  limit *= B**2
  power *= B**2
  while power + 2*x + 1 <= limit:
    power += 2*x + 1
    x += 1
    assert(x**2 == power)
    assert(x**2 <= limit)
# x/B**10 is the desired root 

You can simplify the code further by not turning the power variable into a local variable within the loop. We subtract it from the power variable.

B = 2**8
x = 0
limit = M
for i in range(10):
  limit *= B**2
  power = 0
  while power + 2*x + 1 <= limit:
    power += 2*x + 1
    x += 1
  limit -= power
# x/B**10 is the desired root 

The algorithm could be further optimized if you needed more efficiency. Importantly, it is assumed that the basis is not too large otherwise another type of algorithm would be preferable. Using 256 is fine, however.

Obviously, one can design a faster algorithm, but this one has the advantage of being nearly trivial.

Further reading: A Spigot-Algorithm for Square-Roots: Explained and Extended by Mayer Goldberg

Credit: Thanks to David Smith for inspiring this blog post.

C++ web app with Crow: early scalability results

Last year, I looked at writing small “hello world” web applications in various programming languages (Go, JavaScript, Nim…). Go, using nothing but the standard library, did well.

In these benchmarks, I am just programming an HTTP route that returns a small string (e.g., ‘hello world’). The query is from the host itself. The intent behind such a benchmark is to measure how well an web application might scale in the best of cases. I call such a benchmark ‘simplistic’ because nobody only ever returns just a short string and you do not usually query the server from the host.

At the time, I had wanted to compare with a C++ library, and I ended up trying the lithium framework which scaled very well.

Jake Arkinstall pointed out that he uses Crow, to build web applications in C++. So I decided to take Crow out on a spin.

My simplistic application has only few lines:

#include "crow.h"
int main() {
  crow::SimpleApp app;
  CROW_ROUTE(app, "/simple")([](){
    return "Hello world";

This allows the server to use all threads. You can limit the server to fewer threads by replacing multithreaded() by concurrency(32) to limit (e.g.) the server to 32 threads.

To build it, I use a standard CMakeLists.txt file:

cmake_minimum_required(VERSION 3.15)
project(funserver CXX)
find_package(Crow REQUIRED)
add_executable(server src/server.cpp)
target_link_libraries(server Crow::Crow)

And I use a conan file to specify the dependency:


That is all. Then to build, I issue the following commands in shell:

conan profile detect --force
conan install . --output-folder=build --build=missing
cmake -B build -DCMAKE_TOOLCHAIN_FILE=conan_toolchain.cmake -DCMAKE_BUILD_TYPE=Release
cmake --build build

I assumes that you have C++ compiler, Conan and CMake, but these are standard tools.

After issuing these commands, my server is then running. I use bombardier to hammer the server with requests. On a Linux server with many processors (two  Intel Xeon Gold 6338 CPUs, each made of 32 cores) and much memory, I try increasing the number of simultaneous requests (using the tool bombardier) and looking for errors. As the number of simultaneous queries increase, the system has to sustain both a high number of requests and as well as the processing of the server. You can run my benchmark from my source code and instructions. Your numbers will differ.

simultaneous queries requests/s errors (%)
10 260k 0%
100 315k 0%
1000 380k 0%
10,000 350k 0.002%

I filed an issue with the Crow project regarding the errors. They are very uncommon and only occur under intense stress. They may or may not be the result of a bug.

My performance numbers are comparable to a lithium server. Let us rerun the same tests with lithium using 64 threads to verify:

simultaneous queries requests/s errors (%)
10 90k 0%
100 245k 0%
1000 275k 0%
10,000 240k 0%

Though lithium does not cause any errors even at high queries, it has troubles shutting down after being stressed with 10,000 simultaneous queries.

So it seems that Crow offers state-of-the-art performance. Crow offers HTTP/1.1 and WebSocket support, but it has currently no support for the more recent standards. It has a nice Web site.

Continue reading C++ web app with Crow: early scalability results

Science and Technology links (March 31 2024)

      1. Large language models (e.g., ChatGPT) do better at legal questions than lawyers: Our empirical analysis benchmarks LLMs against a ground truth set by Senior Lawyers, uncovering that advanced models match or exceed human accuracy in determining legal issues (Martin et al.).
      2. Gene therapy-mediated partial reprogramming extends lifespan and reverses age-related changes in aged mice.
      3. Increased vegetation greenness is called greening. Increased atmospheric CO2 is expected to lead to greening since CO2 is effectively a fertilizer. Global greening is a robust process that continued from 2001 to 2020 according to Chen et al. This confirms earlier studies which shows significant greening of the Earth (up 30% in a few decades).
      4. Babylonia was one of the earliest civilizations (established around 1900 BC). The Old Kingdom in Egypt began earlier, around 2500 BC. What was happening elsewhere? We do not really know, but, in America, Caral–Supe was a complex pre-Columbian era society that included as many as thirty major population centers in modern-day Peru. The civilization flourished between the fourth and second millennia BC, with the formation of the first city generally dated to around 3500 BC.
      5. University students have average intelligence according to Uttl et al. They suggest the following consequences: First, universities and professors
        need to realize that students are no longer extraordinary but merely average, and have to adjust curricula and academic standards. Second, employers can no longer rely on applicants with university degrees to be more capable or smarter than those without degrees. Third, students need
        to realize that acceptance into university is no longer an invitation to join an elite group.
      6. Multicellular organisms arose 1.6 billion years ago.
      7. Some stone tools are 1.4 million years old.
      8. Being overweight (abdominal adiposity) is associated with mental decline.
      9. The decimal point might have been invented by mathematician Giovanni Bianchini in the 1440s.
      10. Climate models have been found lacking in a study by Simpson et al. (2023). From the article…

        Water vapor in the atmosphere is expected to rise with warming because a warmer atmosphere can hold more moisture. However, over the last four decades, near-surface water vapor has not increased over arid and semi-arid regions. This may indicate a major model misrepresentation of hydroclimate-related processes.

        Statement by the National Center for Atmospheric Research (NCAR):

        The discrepancy between observations and models indicates a major gap in our understanding and modeling capabilities which could have severe implications for hydroclimate projections, including fire hazard, moving forward. Resolving this discrepancy is an urgent priority.

      11. Good looks are inherited from the parents and associated with substantially higher incomes.
      12. Researchers have rejuvenated the immune systems of mice.
      13. Environmental activism is associated with the dark triad traits (i.e., Machiavellianism, psychopathy, narcissism) and authoritarianism (e.g., top-down censorship).
      14. Solar power plants increase local temperatures.
      15. In countries where there is more equality between women and men, women are less likely to pursue careers in science or engineering.
      16. Among our ancestors, women did hunt occasionally. Nevertheless, there was a clear division of labor.
      17. Psychopaths may have poor planning and be unable to foresee and represent future consequences of their actions.
      18. Northern lights in Northern countries significantly warm the atmosphere, reducing the heating bills in Finland.
      19. Urban environments is where biodiversity is thriving.
      20. Oral contraceptives reduce the clitoral volume, they worsens the pain during intercourse and reduce the frequency of orgasm.
      21. Higher healthcare spending is not associated with greater longevity, but higher wealth is: a $10,000 increase in GDP per capita in a state is associated with 1.13 years more life expectancy.
      22. Asking people to sign an agreement which says they won’t cheat does not reduce cheating.
      23. The term ‘two-spirit’ used to describe a gender specific to indigenous North Americans was coined in the 1990s. Wikipedia warns: Two-spirit, as a term and concept, is neither used nor accepted universally in Native American cultures.
      24. For a long time, diabetes was described as a progressive disease. Once you had diabetes, it was viewed as incurable condition that could only be mitigated. At least in Canada, diabetes is now considered reversible: lifestyle choices (among other things) can reverse diabetes.
      25. Some people have a mutated protein RIMS1 and they exhibit much greater intelligence.
      26. One billion people in the world are obese. Intellectuals in the 1950s and 1960s predicted mass starvation. Most famously Paul R. Ehrlich predicted in his book “The Population Bomb” (1968) that we would see widespread famine and mass starvation. He predicted that 65 million Americans would die of starvation between 1980-1989. He later stated that “India couldn’t possibly feed two hundred million more people by 1980.” Today our greatest problem is not mass starvation in India, but rather the fact that their obesity curves are exponential.
      27. Brain volume has increased during the XXth century in human beings.
      28. Overall, the Antarctic ice shelf area has grown by 5305 km2since 2009. Or nearly 100 times Manhattan Island.
      29. Obesity seems to affect semen quality.
      30. You want to make sure that your ratio of Omega 6 to Omega 3 is low. Think about eating salmon, sardines, and walnuts.
      31. We are often told that modern media is pushing women to dislike their bodies. However, that effect might be exaggerated. There could be deeply rooted evolutionary reasons for women to be anxious about the appearance of their bodies.
      32. Instead of being rewarded, loyal employees are targeted by managers for exploitative practices.
      33. Overbearing parents may cause their children to become emotionally unstable. Overreactive parenting is related to decreases in child agreeableness and emotional stability. There might be wisdom in cultivating freedom.
      34. Oreo Cookies lowers LDL cholesterol more than high-intensity statin therapy.
      35. We found water on the surface of an asteroid.
      36. It is believed that low-dose aspirin has an anti-cancer effect. It might be due to its suppression of some platelets.

Fast and concise probabilistic filters in Python

Sometimes you need to filter out or filter in data quickly. Suppose that your employer maintains a list of forbidden passwords or URLs or words. You may store them in a relational database and query them as needed. Unfortunately, this process can be slow and inefficient.

A better approach might be to use a probabilistic filter. A probabilistic filter is a sort of ‘approximate set’. You can ask it whether a key is present in the set, and if it is present, then you will always get ‘true’ (the correct answer). However, when the key is not present, you may still get ‘true’, although with a low probability. So the probabilistic filter is sometimes wrong. Why would you accept a data structure that is sometimes wrong? Because it can be several times smaller and faster than querying directly the actual set.

The best known probabilistic filter is the Bloom filter, but there are many others. For example, we recently presented the binary fuse filters which are smaller and faster than Bloom filters, for large and immutable sets.

The pyxorfilter module in Python is an implementation of the binary fuse filters. It provides support for several filter types but both Fuse8 and Fuse16 are interesting if you have fairly large sets. They provide respectively a 0.39% and 0.0015% false probability rate. So a Fuse16 filter is almost nearly correct. Why would you prefer Fuse8? Because it uses half the memory.

We can construct a probabilistic filter in Python like so with the pyxorfilter filter:

from pyxorfilter import Fuse8
data = [uuid.uuid4() for i in range(2000000)]

filter = Fuse8(len(data))

Once it is done, you can be certain that all the content of your initial set is in the filter:

for d in data:
  assert filter.contains(d)

You can save the filter on disk and check how much memory is used…

f = open(filename, 'wb')

If your set is large enough (say 1000,000 elements), you will find that the memory usage is about 9 bits per entry. It grows a bit larger per entry as the set gets smaller. For smaller sets, the pyxorfilter module offers an alternative (Xor8) that can be slightly more efficient in these cases.

How do you know if you can trust the filter? Just query random inputs (highly likely not to be present) and see how many falsely appear to be in the set:

# estimate false positive rate
N = 1000000
count = 0
for i in range(N):
count += filter.contains(uuid.uuid4())
fpp = count/N*100.0

As I already implied, if you replace Fuse8 by Fuse16, then the memory usage per element goes up to about 18 bits, but the false positive rate is far lower: 0.00200%.

I produced a small benchmark. On my laptop, I get that you get over 1 million queries per second (each time checking the presence of a string). On an Intel-based server, I get a lower number, so about half a million per second.

For binary fuse filters, it does not matter whether the element is in the set or not as far as performance goes, so I use random inputs. When using a Bloom filter (say), you would typically get worse performance when the elements are in the set.

The pyxorfilter  module was created Amey Narkhede. It still early days. I expect you can install pyxorfilter the usual way (pip install pyxorfilter) under x64 Linux. Unfortunately, Windows and other platfomrs, there are issues getting the module installed (see issue 10) since binary modules are not available for all platforms. The pip installer should try to install it from the source code. If you are a Python hacker, you can build it from source relatively easily:

git clone --recurse-submodules
cd pyxorfilter
python build_ext
python install

I am sure Amey would appreciate it if experienced Python hackers could help resolve the few remaining issues.

There are functionalities that pyxorfilter misses. Currently, you can save the filter to disk and recover it later. Sadly, to use it, you need to load the whole filter in memory. That is not needed. It might be more suitable to use memory file mapping or even other lower-level input-output operations.

What if you do not care about Python? You can use the xor and binary fuse filters in Go, C or C++, Zig, Rust, etc. I just love working in Python when I can.

Passing recursive C++ lambdas as function pointers

In modern C++, as in many popular languages, you can create ‘lambdas’. Effectively, they are potentially anonymous function instances that you can create on the fly as you are programming, possibly inside another function. The following is a simple example.

auto return1 = [](int n) -> int { return 1; };

What about recursive functions? At first I thought you could do…

auto fact = [](int n) -> int {
 if (n == 0) {
   return 1;
 } else {
  return n * fact(n - 1);

Sadly it fails. What seems to be happening is that while it recognizes the variable ‘fact’ within the definition of ‘fact’, it cannot use it without knowing its type. So you should specify the type of the ‘fact’ right away. The following will work:

std::function<int(int)> fact = [](int n) -> int {
  if (n == 0) {
    return 1;
  } else {
    return n * fact(n - 1);

But using std::function templates may add complexity. For example, what if you have a function that takes a function as a parameter without using std::function, such as…

void print(int(*f)(int)) {
  for(int k = 1; k < 10; ++k) {
   std::cout << "Factorial of " << k << " is " << f(k) << std::endl;

Then you would want to call print(fact), but it will not work directly. It may complain like so:

No known conversion from 'std::function' to 'int (*)(int)

So let us avoid the std::function as much as possible:

int (*factorial)(int) = [](int n) -> int {
  if (n == 0) {
    return 1;
  } else {
    return n * factorial(n - 1);

And then everything works out fine:

    print(factorial); // OK

Let me finish with a word of caution: functional programming is sophisticated, but it has downsides. One potential downside is performance. Let us consider this conventional code:

int factorialc(int n) {
  if (n == 0) {
    return 1;
  } else {
    return n * factorialc(n - 1);
int functionc() {
  return factorialc(10);

Most compilers should produce highly optimized code in such a scenario. In fact, it is likely that the returned value of ‘functionc’ gets computed a compile time. The alternative using lambdas might look as follows:

int (*lfactorial)(int) = [](int n) -> int {
  if (n == 0) {
    return 1;
  } else {
    return n * lfactorial(n - 1);

int functionl() {
  return lfactorial(10);

Though the results will depend on your system, I would expect far less efficient code in general.

Thus when programming in C++,  if you use lambdas in performance critical code, run benchmarks or disassemble your function to make sure that you have, indeed, zero-cost abstraction.

My source code is available.

Credit: Thanks to Ca Yi, Yagiz Nizipli and many X users for informing this post.

Further reading: Recursive lambdas from C++14 to C++23