Skip to content

Instantly share code, notes, and snippets.

@FedericoPonzi
Last active October 22, 2020 13:32
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 FedericoPonzi/6020c5277457f5cee87a0640fff48353 to your computer and use it in GitHub Desktop.
Save FedericoPonzi/6020c5277457f5cee87a0640fff48353 to your computer and use it in GitHub Desktop.
Amount of recursive function calls before SO in different languages
#include <stdio.h>
int f(int v) {
printf("%d\n", v);
return 0 + f(v + 1);
}
int main() {
f(0);
return 0;
}
/**
Compiled with: `gcc stack.c`
f() is executed 261638 times before SO.
Compiled with:
gcc -O2 stack.c
the recursion is stripped away.
**/
class Stack {
public static int f(int v) {
System.out.println(v);
return 0 + f(v + 1);
}
public static void main(String[] args) {
try{
f(0);
}catch(java.lang.StackOverflowError e){
System.out.println("\nStackoverflow.");
}
}
}
/**
With java 1.8.0_171, f() is executed between 16892 and 18332 times before SO.
With java 10.0.1 f() is executed between 9121 and 17389 times before SO.
**/
value = 0
def f(v):
global value
value = v
print(v)
return 0 + f(v + 1)
if __name__ == "__main__":
try:
f(0)
except RuntimeError as e:
print("Stackoverflow. {}".format(value))
'''
With python3, f() is executed 996 times before SO.
With python2, f() is executed 998 times before SO.
'''
fn f(v: i32) -> i32 {
println!("{}", v);
return 0 + f(v + 1);
}
fn main() {
f(0);
}
"""
rust 1.42.0: ~58211
"""

The stack is not an infinite resource - this limit the times a recursive function call can be made.

Here there are some statistics about languages I use, feel free to add more.

ulimit -s 8192
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment