Skip to content

Instantly share code, notes, and snippets.

@YoshiTheChinchilla
Created October 13, 2020 05:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save YoshiTheChinchilla/97a41fa4e94fbfb8c70abccfe94974f6 to your computer and use it in GitHub Desktop.
Save YoshiTheChinchilla/97a41fa4e94fbfb8c70abccfe94974f6 to your computer and use it in GitHub Desktop.
nom the parser performance comparison between spaces and tabs https://github.com/Geal/nom
use std::time::Instant;
use nom::character::complete::*;
use nom::error::ParseError;
use nom::{AsChar, InputIter, InputTakeAtPosition, Slice};
fn parse_spaces<T, E: ParseError<T>>(mut input: T) -> i32
where
T: InputTakeAtPosition + InputIter + Slice<std::ops::RangeFrom<usize>>,
<T as InputTakeAtPosition>::Item: AsChar + Clone,
<T as InputIter>::Item: AsChar,
{
let mut count = 0;
while let Ok((s, _)) = space1::<T, E>(input) {
match newline::<T, E>(s) {
Ok((s, _)) => {
input = s;
count += 1;
}
_ => break,
}
}
count
}
fn parse_tabs<T, E: ParseError<T>>(mut input: T) -> i32
where
T: InputTakeAtPosition + InputIter + Slice<std::ops::RangeFrom<usize>>,
<T as InputTakeAtPosition>::Item: AsChar + Clone,
<T as InputIter>::Item: AsChar,
{
let mut count = 0;
while let Ok((s, _)) = tab::<T, E>(input) {
match newline::<T, E>(s) {
Ok((s, _)) => {
input = s;
count += 1;
}
_ => break,
}
}
count
}
fn main() {
let times = 22;
let space_str = " \n".repeat(2usize.pow(times));
let two_spaces_str = " \n".repeat(2usize.pow(times));
let three_spaces_str = " \n".repeat(2usize.pow(times));
let four_spaces_str = " \n".repeat(2usize.pow(times));
let tabs_str = "\t\n".repeat(2usize.pow(times));
let now = Instant::now();
parse_spaces::<_, ()>(space_str.as_str());
println!("spaces_str: {}ms", now.elapsed().as_millis());
let now = Instant::now();
parse_spaces::<_, ()>(two_spaces_str.as_str());
println!("two_spaces_str: {}ms", now.elapsed().as_millis());
let now = Instant::now();
parse_spaces::<_, ()>(three_spaces_str.as_str());
println!("three_spaces_str: {}ms", now.elapsed().as_millis());
let now = Instant::now();
parse_spaces::<_, ()>(four_spaces_str.as_str());
println!("four_spaces_str: {}ms", now.elapsed().as_millis());
let now = Instant::now();
parse_tabs::<_, ()>(tabs_str.as_str());
println!("tabs_str: {}ms", now.elapsed().as_millis());
}
spaces_str: 8798ms
two_spaces_str: 9693ms
three_spaces_str: 11965ms
four_spaces_str: 13677ms
tabs_str: 5345ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment