-
Notifications
You must be signed in to change notification settings - Fork 10
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add benches #13
Comments
What was ChatGPT's code? |
Sure! #![feature(test)]
extern crate test;
use convert_case::{Case, Casing};
fn to_camel(s: &str) -> String {
let mut result = String::with_capacity(s.len());
let mut capitalize_next = false;
for c in s.chars() {
if c == ' ' || c == '_' || c == '-' {
capitalize_next = true;
} else {
if capitalize_next {
result.push(c.to_ascii_uppercase());
capitalize_next = false;
} else {
result.push(c.to_ascii_lowercase());
}
}
}
result
}
fn to_snake(s: &str) -> String {
let mut result = String::with_capacity(s.len());
let mut upper_count = 0;
for (i, c) in s.chars().enumerate() {
if c.is_uppercase() {
upper_count += 1;
if i > 0 && upper_count < 2 {
result.push('_');
}
result.push(c.to_ascii_lowercase());
} else {
if upper_count > 1 {
if let Some(last_c) = result.pop() {
result.push('_');
result.push(last_c);
}
}
upper_count = 0;
result.push(c);
}
}
result
}
#[cfg(test)]
mod tests {
use super::*;
use test::Bencher;
#[test]
fn it_works() {
assert_eq!("ronnieJamesDio", "Ronnie_James_dio".to_case(Case::Camel));
assert_eq!("ronnie_james_dio", "ronnieJamesDio".to_case(Case::Snake));
assert_eq!("ronnieJamesDio", to_camel("Ronnie_James_dio"));
assert_eq!("ronnie_james_dio", to_snake("ronnieJamesDio"));
}
#[bench]
fn bench_to_camel1(b: &mut Bencher) {
b.iter(|| "Ronnie_James_dio".to_case(Case::Camel));
}
#[bench]
fn bench_to_camel2(b: &mut Bencher) {
b.iter(|| to_camel("Ronnie_James_dio"));
}
#[bench]
fn bench_to_snake1(b: &mut Bencher) {
b.iter(|| "ronnieJamesDio".to_case(Case::Snake));
}
#[bench]
fn bench_to_snake2(b: &mut Bencher) {
b.iter(|| to_snake("ronnieJamesDio"));
}
}
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I compared this crate with ChatGPT's code. And ChatGPT's code was faster than this one.
Maybe we need to optimize the algorithm for converting a case.
The text was updated successfully, but these errors were encountered: