Profile Picture

Assorted tech

Hi, my name is Spencer. I'm a CS graduate focused on systems programming, Linux, and low-complexity design. Other interests: metal, hiking, guitar, rationality.

feed | contact

Use Logarithms to Get Integer Length

Calendar icon March 1, 2024

Clock icon 1 min read

Folder icon #software #rust #math #programming in tech

Introduction

Doing math with logarithms can make your code ~6 OOM faster by preventing an integer -> string conversion in two cases. This “trick” might be obvious to programmers with a math background but I suspect many people don’t realize that it is an option. These examples use rust, but translate directly to other languages.

Counting Digits

The immediately obvious way to do this is as follows:

let num: i32 = 98234812;
num.to_string().len()
// => 8

However, this method is much faster (~6 OOM / ~1,000,000x faster):

let num: i32 = 98234812;
1 + num.checked_ilog10().unwrap() as usize
// => 8

Comparison

Why is it so much faster? Let’s have a look at the disassembled version on the Compiler Explorer https://godbolt.org/z/1GMa9a5se (normally you should run when somebody says that, but you trust me right?)

Look how many instructions that is! The disassembled version of the version using .to_string() and .len() is nearly 2000k lines long!

Now check out the second version: https://godbolt.org/z/3Pz331co5. This one is only 108 lines.

Comments