hfiguiere / leftpad-rs

leftpad, in rust.
BSD 2-Clause "Simplified" License
17 stars 7 forks source link

Improve performance for long strings by preallocating the needed memory #9

Open iscgar opened 7 years ago

iscgar commented 7 years ago

Instead of causing a regrow of the String's underlying buffer by the push loop and then by pushing s, use with_capacity to preallocate the memory.

iscgar commented 7 years ago

Oops. When I forked the repository #6 didn't exist, so I created this PR. Sorry. Choose whichever suits you best (though I should note that my version was consistently a few ns faster in my benchmarks).

iscgar commented 7 years ago

This is actually silly, because len() returns the amount of bytes the str occupies, where people expect it to work on Unicode codepoints (.chars().chount() does that, but with UTF-8 it takes O(n) time). Rust is doing the right thing here, because the "length" of a string doesn't really mean anything. In fact, when people talk about string length they actually mean the amount of grapheme clusters, which most string libraries don't provide (the unicode-segmentation crate provides that functionality, but it's even slower).

Just an example of how even a simple thing like leftpad is incorrectly defined 😆

hfiguiere commented 7 years ago

leftpad-rs was written as a joke. So hasty that the first implementation didn't even match what I was trying to clone.