Subject: 29.0.50; cc-mode fontification makes CPU at 100%
From: Zhiwei Chen <[email-masked]>
To: [email-masked]
Date: Sat, 06 Nov 2021 19:02:03 +0800
List-Id: <debbugs-submit.debbugs.gnu.org>

In GNU Emacs 29.0.50 (build 1, x86_64-pc-linux-gnu, GTK+ Version 3.24.30, cairo version 1.17.4)
 of 2021-11-06 built on lilydjwg
Repository revision: 5a013838746c160cb296e0bc80a11795d2538f9a
Repository branch: master
Windowing system distributor 'The X.Org Foundation', version 11.0.12013000
System Description: Arch Linux

It's originally reported at emacs-china.org [1].

emacs -Q, then open the following c++ snippet.

#+begin_src C++
#include <iostream>
#include <vector>

#define MAX 10000

void merge(std::vector<int> array, int p, int q, int r) {
  int len_1 = q - p + 1;
  int len_2 = r - q;
  int a = 0;
  int b = 0;
  std::vector<int> left_array(len_1 + 2, 0);
  std::vector<int> right_array(len_2 + 2, 0);
  for (int i = 0; i < len_1; ++i) {
    left_array[i] = array[p + i - 1];
  }
  for (int i = 0; i < len_2; ++i) {
    right_array[i] = array[q + i];
  }
  left_array[len_1 + 1] = MAX;
  right_array[len_2 + 1] = MAX;
  for (int i = p; i < r + 1; ++i) {
    if (left_array[a] <= right_array[b]) {
      array[i] = left_array[a];
      ++a;
    } else {
      array[i] = right_array[b];
      ++b;
    }
  }
}

void merge_sort(std::vector<int> array, int p, int r) {
  if (p < r) {
    int q = (p + r) / 2;
    merge_sort(array, p, q);
    merge_sort(array, q + 1, r);
    merge(array, p, q, r);
  }
}

int main() {
  std::vector<int> array = {3, 1, 2, 6, 4, 5};
  merge_sort(array, 0, array.size() - 1);
  for (auto i : array) {
    std::cout << i << "\n";
  }
  return 0;
}
#+end_src

The profiler shows `jit-lock-function' costs 62% CPU time.

#+begin_src text
2952  62% - redisplay_internal (C function)
        2936  62%  - jit-lock-function
        2936  62%   - jit-lock-fontify-now
        2920  62%    - jit-lock--run-functions
        2920  62%     - run-hook-wrapped
        2920  62%      - #<compiled 0x19b62a583670403d>
        2920  62%       - font-lock-fontify-region
        2920  62%        - c-font-lock-fontify-region
        2605  55%         - font-lock-default-fontify-region
        2534  53%          - font-lock-fontify-keywords-region
        1339  28%           - c-font-lock-declarations
        1317  27%            - c-find-decl-spots
         593  12%             + #<compiled 0x62f8c10afa44432>
         582  12%             + c-bs-at-toplevel-p
#+end_src

[1]: https://emacs-china.org/t/emacs-c/18814

-- 
Zhiwei Chen