Skip to content

Performance

Complexity, memory, profile reuse and Unicode code-point semantics for strsimpy 0.5.0.

These are asymptotic bounds taken from the 0.5.0 implementations, not wall-clock benchmarks. They ignore constant factors and assume expected O(1) hash-table operations. Measure representative inputs before making a production decision.

Notation

Symbol Meaning
m, n Input lengths in Unicode code points
k Shingle size
D0, D1 Number of distinct shingles in each profile, at most max(len - k + 1, 0)
A, B Number of whitespace-separated tokens
L Typical token length
sigma Number of distinct characters in the alphabet of the inputs

Complexity by family

Measure or family Time Extra memory Notes
Levenshtein, NormalizedLevenshtein O(m*n) O(n) Two rolling rows; normalized divides by the longer length.
WeightedLevenshtein O(m*n) O(n) Two rolling rows, but cost functions may be Python callables, so constant factors are much higher.
Damerau O(m*n) O(m*n) Uses a full dynamic-programming matrix.
OptimalStringAlignment O(m*n) O(m*n) Builds the full matrix for the distance; alignment() also needs it.
JaroWinkler, StrCmp95 O(m*n) worst O(m+n) The matching window is usually narrower than the worst case; Strcmp95 normalizes both inputs first.
MLIPNS O(max(m,n)) O(m+n) One Hamming-style pass plus up to max_mismatches bounded rounds.
LongestCommonSubsequence, MetricLCS O(m*n) O(n) Two rolling rows; MetricLCS calls the LCS length.
RatcliffObershelp O(m*n*min(m,n)) worst O(n) plus an explicit stack Each longest-common-substring pass is O(m*n); repetitive inputs approach the worst case.
NGram O(m*n) O(m+n) Pads the first string and keeps two rolling rows.
NeedlemanWunsch.score, SmithWaterman.score, Gotoh.score O(m*n) O(min(m,n)) Rolling rows only; Gotoh keeps three.
NeedlemanWunsch.alignment, SmithWaterman.alignment, Gotoh.alignment O(m*n) O(m*n) Full traceback matrix, or three matrices for Gotoh.
QGram.distance_profile, Cosine.similarity_profiles O(D0 + D1) O(D0 + D1) for QGram’s union set; O(1) beyond profiles for Cosine Compare cached profiles instead of re-shingling.
QGram.distance, Cosine.similarity, Jaccard, SorensenDice, OverlapCoefficient, Tversky, Tanimoto O(m+n) O(D0 + D1) Profile construction dominates; set operations add expected linear work.
Bag O(m+n) O(sigma) Character counts only; no shingles or edit matrix.
MongeElkan O(A*B*L*L) O(A+B+L) Every token pair is compared with Jaro-Winkler or normalized Levenshtein, each O(L*L).
NormalizedCompressionDistance O(m+n) O(1) Four RLE scans: each input and both concatenation orders.
SIFT4 O(m*n) worst; near-linear with a small maxoffset O(m+n) Stores token lists and an offset stack.

The set measures include Jaccard, SorensenDice, OverlapCoefficient, Tversky and Tanimoto. They and Cosine share the same whitespace normalization before profile construction.

Score versus alignment memory

The alignment classes expose two different cost profiles:

  • score(s0, s1) keeps rolling rows and uses O(min(m, n)) memory. Call this when you only need the number.
  • alignment(s0, s1) builds the full traceback structure, which is O(m*n). Call it only when you need the operations.

OptimalStringAlignment.distance() and Damerau.distance() already use full matrices in 0.5.0, unlike Levenshtein and LCS, which roll rows. There is no rolling-row option for OSA or Damerau in this release, so budget O(m*n) memory if you use them on long inputs.

Shingle profiles and reuse

QGram and Cosine can compare precomputed profiles. This is the main optimization for pairwise comparisons over a large corpus: build each profile once, then reuse it for every pair.

from strsimpy import Cosine, QGram

cosine = Cosine(2)
p0 = cosine.get_profile("My first string")
p1 = cosine.get_profile("My other string...")
print(cosine.similarity_profiles(p0, p1))

qgram = QGram(2)
print(qgram.distance_profile(qgram.get_profile("ABCD"), qgram.get_profile("ABCE")))
0.5161854012087639
2

Rules for safe profile reuse:

  • Use the same k for every profile in a comparison. A profile is a plain dictionary and does not record the shingle size that produced it.
  • Profiles are already whitespace-normalized: runs of Python whitespace are collapsed to one ASCII space before shingling. Do not re-normalize in a way that changes the input.
  • QGram.distance_profile() and Cosine.similarity_profiles() accept any Python mapping of shingle to count, including MappingProxyType, UserDict and Counter.
  • The other shingle measures expose get_profile(), but in 0.5.0 their similarity() and distance() methods accept strings, not profiles. Caching a profile for Jaccard, SorensenDice, OverlapCoefficient, Tversky or Tanimoto does not avoid re-shingling inside those methods.
  • Profile memory grows with the number of distinct shingles D, not just the input length. Very long strings with a small k can produce many keys.

NGram does not use the shingle profile and does not normalize whitespace.

Unicode code-point semantics

Every algorithm operates on Unicode scalar values, matching Python’s len() and indexing. A CJK character and an emoji each count as one character, while a combining sequence counts as its separate code points.

from strsimpy import Bag, Levenshtein

print(Levenshtein().distance("😀", "😁"))
print(Levenshtein().distance("A", "a"))
print(Levenshtein().distance("é", "é"))
print(Bag().distance("上海", "海上海"))
1
1
2
1

The third pair is a precomposed é against a decomposed e plus combining acute accent; the two are different code-point sequences. The library does not apply Unicode normalization (NFC or NFD) automatically. Normalize inputs yourself if canonically equivalent text should compare equal.

Other consequences:

  • Comparisons are case-sensitive, except for Strcmp95, which uppercases both inputs. Levenshtein() therefore scores "A" against "a" as 1.
  • Bag counts characters, not bytes or grapheme clusters.
  • Shingle profiles are keyed by code-point substrings; whitespace is normalized before windowing.
  • RLE in NormalizedCompressionDistance runs over code points and counts the compressed size in characters, so a multi-byte character counts once.
  • MongeElkan tokenization uses Unicode whitespace as separators.

Practical guidance

  • Filter by length first. The absolute length difference is a lower bound for Levenshtein distance.
  • Use Bag distance as a cheap metric filter for edit distance, and QGram as a lower bound when profiles are already available.
  • For pairwise searches, compute score() first and request alignment() only for the pairs you need to explain.
  • Avoid RatcliffObershelp on long, highly repetitive text unless you have measured its worst-case behavior on that data.
  • Treat SIFT4 as a heuristic. Its scale depends on maxoffset, tokenization and evaluators; benchmark on representative inputs.
  • NCD with RLE is linear, but RLE is a weak compressor. Its values are not comparable to NCD computed with another compressor, and they are not guaranteed to lie in [0, 1].

Type to search…

↑↓ navigate↵ selectEsc close