string_literal_benchmark.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include <benchmark/benchmark.h>
  5. #include "toolchain/lexer/string_literal.h"
  6. namespace Carbon::Testing {
  7. namespace {
  8. static void BM_ValidString(benchmark::State& state, std::string_view introducer,
  9. std::string_view terminator) {
  10. std::string x(introducer);
  11. x.append(100000, 'a');
  12. x.append(terminator);
  13. for (auto _ : state) {
  14. LexedStringLiteral::Lex(x);
  15. }
  16. }
  17. static void BM_ValidString_Simple(benchmark::State& state) {
  18. BM_ValidString(state, "\"", "\"");
  19. }
  20. static void BM_ValidString_Multiline(benchmark::State& state) {
  21. BM_ValidString(state, "\"\"\"\n", "\n\"\"\"");
  22. }
  23. static void BM_ValidString_Raw(benchmark::State& state) {
  24. BM_ValidString(state, "#\"", "\"#");
  25. }
  26. BENCHMARK(BM_ValidString_Simple);
  27. BENCHMARK(BM_ValidString_Multiline);
  28. BENCHMARK(BM_ValidString_Raw);
  29. static void BM_IncompleteWithRepeatedEscapes(benchmark::State& state,
  30. std::string_view introducer,
  31. std::string_view escape) {
  32. std::string x(introducer);
  33. // Aim for about 100k to emphasize escape parsing issues.
  34. while (x.size() < 100000) {
  35. x.append("key: ");
  36. x.append(escape);
  37. x.append("\"");
  38. x.append(escape);
  39. x.append("\"");
  40. x.append(escape);
  41. x.append("n ");
  42. }
  43. for (auto _ : state) {
  44. LexedStringLiteral::Lex(x);
  45. }
  46. }
  47. static void BM_IncompleteWithEscapes_Simple(benchmark::State& state) {
  48. BM_IncompleteWithRepeatedEscapes(state, "\"", "\\");
  49. }
  50. static void BM_IncompleteWithEscapes_Multiline(benchmark::State& state) {
  51. BM_IncompleteWithRepeatedEscapes(state, "\"\"\"\n", "\\");
  52. }
  53. static void BM_IncompleteWithEscapes_Raw(benchmark::State& state) {
  54. BM_IncompleteWithRepeatedEscapes(state, "#\"", "\\#");
  55. }
  56. BENCHMARK(BM_IncompleteWithEscapes_Simple);
  57. BENCHMARK(BM_IncompleteWithEscapes_Multiline);
  58. BENCHMARK(BM_IncompleteWithEscapes_Raw);
  59. } // namespace
  60. } // namespace Carbon::Testing